playing dynamic sound clips in browser - php

I've never delt with sound clips and im wanting to play one via an event.
I have a file which has a snippet like so:
if( $get['0002'] == 'mu' ) {
switch( $get['0000'] ) {
case 'mp3': header('Content-Type: audio/mp3'); break;
case 'wav': header('Content-Type: audio/x-wav'); break;
default: break;
}
echo file_get_contents('./folder-name/' . $get['0001'] . '.' . $get['0000'] );
exit;
}
and on the page I fave this button;
<input type="button" value="Play Sound" onClick="EvalSound('sound1')" >
and this hidden away in the background
<embed src="./?0000=wav&0001=0001&0002=mu" autostart=false width=0 height=0 id="sound1" enablejavascript="true">
and the js being;
<script>
function EvalSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.Play();
}
</script>
This does not seem to work and I believe it has something to do with the PHP headers. Could someone please point me in the right direction, as it would be much appreciated.

Please do some testing here with: http://www.phon.ucl.ac.uk/home/mark/audio/play.htm
On firefox I get an error for the Play() function.
Use something like firebug to give you more information.
If everything works then start debugging your php script.

Related

My PHP function won't return the response to AJAX until the process finishes

I need the PHP response as it is outputted on the php echo.
But when I have a process running, it returns all at once, only after the process has ended.
Is there a way around this?
Thank you in advance
Edit:
This is the ajax after getting the response:
// callback handler called on success
request.done(function (response) {
$('#add--response').html(response);
});
This is the PHP
$count=0;
foreach ($_POST['URLS'] as $url) {
if(!empty($url)){
echo '<div id="conversionSuccess">here is the progress bar for the download</div>';
if (<here I download a file that takes a long time>)
{
echo "success";
}
else
{
echo 'Error!';
}
$count++;
echo "count: ".$count."<br>";
}
}
I want the progress bar visible before the file finishes downloading.
I hope now it makes sense
Without your code, its hard to understand what you're asking or how to help. For better practice, please attach code in your next questions.
However, I'd approach this by building the string in a way you can then later split it and use the response: this meaning -
$response = "";
$response .= $outputOne . "/";
$response .= $outputTwo . "/";
echo $reponse;
Inside your JQuery:
var output = reponse.split("/");
output now becomes an array of each of your output's.
Hope this was relevant and helped.

style die() error message

How do I make the die() message to echo in a certain place in the HTML section of the same page?
$files = array();
$upload = $_FILES['upload']['tmp_name'];
foreach($upload as $uploaded){
if(!empty($uploaded)) {
if(isset($uploaded)){
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime= finfo_file($finfo, $uploaded);
switch($mime) {
case 'application/pdf':
break;
default:
die('pdf file only.');
break;
}
}
}
}
die will immediately stop execution and send anything in buffers to the browser.
Personally, I like to do something like this:
function halt($str="") {
if( $str) echo "<div class=\"server_notice\">".$str."</div>";
require("template/foot.php");
exit;
}
How about don't just use die, do something to insert html there and then die.
Alternatively, you have register_shutdown_function (Documentation: http://php.net/manual/es/function.register-shutdown-function.php) which will allow you to do things right after the script is ended with die;
There is no way to do that. die() or exit() will stop executing of your script.
Thouh, you can make some error reporting system.
$lastError = null
Then do what you want and set this error.
Then you can check it in some place:
if ($lastError == 2){
echo "The file is no in PDF format" ;
} //and so on.
Also you could create some constants like:
define("ERROR_WRONG_FORMAT", 2); //Make the error clear.
You'll need to echo out div tags and then position them using CSS.
die('<div id="error">pdf file only.</div>');
Then add the following text to your CSS:
#error{position:absolute;top:10;left:10;}
You'll need to change the top and left values depending on where you wnat them to be.
If you don't know what CSS is, I suggest you watch TheNewBoston's tutorials on YouTube!

AJAX XMLHttpRequest 'bouncing back' when sending vars to PHP

I apologize if I don't articulate my problem correctly, but I'll give it my best shot. I've been looking all over the net for info which can help me with this issue, to no avail.
Just a bit of background. I'm an experienced web coder, though haven't done webwork in a few years prior to this, I have done a fair bit of work in PHP and javascript before and these days I work with C++, so I'm fairly experienced with programming principles.
I'm building some blog software, and inb4wordpress and jQuery, I simply don't care. So spare it please... I'm loading some blog entries into an element through a simple AJAX request function. This function is detailed below: ( It's been changed to a 3 function example I found on the net while I was trying to debug this issue, no one's 'simple' code seems to work. )
The problem is detailed beneath the code.
var httpObject = null;
function getHTTPObject(){
if(window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if(window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function setOutput(){
if(httpObject.readyState == 4){
document.getElementById("entries").innerHTML = httpObject.responseText;
}
}
function loadEntries(s) {
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET","entries.php?" + s,true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
Simple stuff? I can't seem to see any errors there. This is how the function is called:
<div id='entries'>
<script type="text/javascript">
loadEntries('blog=<?php echo $process['id']; ?>&page=0');
</script>
</div>
also simple.
Here's the PHP code for 'entries.php':
<?php
require_once('inc/bloginc.php');
if(isset($_GET['page'])) {
$page = intval($_GET['page']);
} else $page = 0;
$entries = 3;
$init = $page * $entries;
$limit = $entries + $init;
if(!isset($_GET['blog'])) die("WTF DIE");
else $blog = mysql_real_escape_string($_GET['blog']);
$tag = '';
if(isset($_GET['tag'])) {
$tag = mysql_real_escape_string($_GET['tag']);
echo "<span class='blogEntryBody'>viewing entries tagged with: '" . $tag . "' / <a href='' onclick=\"";
echo "loadEntries('blog=" . $blog . "')";
echo "\">clear?</a></span></br>";
echo "<hr>";
}
$numposts = nResults($blog, $tag);
buildEntries(getEntries($blog, $tag, $init, $limit));
if($numposts > $entries) {
echo "</br><span class='blogEntryBody'>";
if($page > 0) {
echo "<a href='' onClick=\"";
echo "loadEntries('blog=" . $blog;
if(isset($_GET['tag'])) echo "&tag=" . $tag;
echo "&page=" . (--$page) . "')";
echo "\">Previous Entries</a>";
echo " / ";
}
echo "<a href='' onClick=\"";
echo "loadEntries('blog=" . $blog;
if(isset($_GET['tag'])) echo "&tag=" . $tag;
echo "&page=" . (++$page) . "')";
echo "\">Next Entries</a>";
echo "<br></span>";
}
?>
okay, now here's where things get tricky:
When sending vars to 'entries.php', such as: entries.php?blog=walk&page=1
They intermittently work, some of these work, but some don't.
I know it's not the PHP code, since loading entries.php up in a new window and manually passing these vars elicits the desired results. What happens is that the HTTP GET request returns 'undefined' in Firefox webdev console, such as this:
[14:47:33.505] GET http://localhost/meg/entries.php?blog=walk&tag=lorem [undefined 2ms]
^ The 'tag' variable usually works, it's normally the 'page' variable that sends everything haywire.
What happens is, after clicking 'next page', you quickly see a blank div, and then it quickly bounces back to the previous state. You see all this loading in the console. It'll return 'undefined' then reload the previous state. Which is just puzzling.
I don't understand why this would be occurring.
I hope I've provided enough information, and set it out in an easy to understand format. I'm new to asking questions. I usually just 'googleit' or RTM. But I think maybe this time someone else will have seen this before.
Oh, and I've tested in chrome, same issue. I'm really puzzled, but open to the possibility that maybe I've overlooked something small and crucial.
Thanks!
Well it happens few times that ajax doesn't works in chrome & explorer so my suggestion to use jquery because in jquery they already include codes for explorer and chrome.
you can use
$.get , $.post or $.ajax methods easily.

PHP variable from external .php file, inside JavaScript?

I have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.

Getting the screen resolution using PHP

I need to find the screen resolution of a users screen who visits my website?
You can't do it with pure PHP. You must do it with JavaScript. There are several articles written on how to do this.
Essentially, you can set a cookie or you can even do some Ajax to send the info to a PHP script. If you use jQuery, you can do it something like this:
jquery:
$(function() {
$.post('some_script.php', { width: screen.width, height:screen.height }, function(json) {
if(json.outcome == 'success') {
// do something with the knowledge possibly?
} else {
alert('Unable to let PHP know what the screen resolution is!');
}
},'json');
});
PHP (some_script.php)
<?php
// For instance, you can do something like this:
if(isset($_POST['width']) && isset($_POST['height'])) {
$_SESSION['screen_width'] = $_POST['width'];
$_SESSION['screen_height'] = $_POST['height'];
echo json_encode(array('outcome'=>'success'));
} else {
echo json_encode(array('outcome'=>'error','error'=>"Couldn't save dimension info"));
}
?>
All that is really basic but it should get you somewhere. Normally screen resolution is not what you really want though. You may be more interested in the size of the actual browser's view port since that is actually where the page is rendered...
Directly with PHP is not possible but...
I write this simple code to save screen resolution on a PHP session to use on an image gallery.
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
} else if(isset($_REQUEST['width']) AND isset($_REQUEST['height'])) {
$_SESSION['screen_width'] = $_REQUEST['width'];
$_SESSION['screen_height'] = $_REQUEST['height'];
header('Location: ' . $_SERVER['PHP_SELF']);
} else {
echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}
?>
New Solution If you need to send another parameter in Get Method (by Guddu Modok)
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
print_r($_GET);
} else if(isset($_GET['width']) AND isset($_GET['height'])) {
$_SESSION['screen_width'] = $_GET['width'];
$_SESSION['screen_height'] = $_GET['height'];
$x=$_SERVER["REQUEST_URI"];
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['width']);
unset($params['height']);
$string = http_build_query($params);
$domain=$_SERVER['PHP_SELF']."?".$string;
header('Location: ' . $domain);
} else {
$x=$_SERVER["REQUEST_URI"];
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['width']);
unset($params['height']);
$string = http_build_query($params);
$domain=$_SERVER['PHP_SELF']."?".$string;
echo '<script type="text/javascript">window.location = "' . $domain . '&width="+screen.width+"&height="+screen.height;</script>';
}
?>
PHP is a server side language - it's executed on the server only, and the resultant program output is sent to the client. As such, there's no "client screen" information available.
That said, you can have the client tell you what their screen resolution is via JavaScript. Write a small scriptlet to send you screen.width and screen.height - possibly via AJAX, or more likely with an initial "jump page" that finds it, then redirects to http://example.net/index.php?size=AxB
Though speaking as a user, I'd much prefer you to design a site to fluidly handle any screen resolution. I browse in different sized windows, mostly not maximized.
Easiest way
<?php
//-- you can modified it like you want
echo $width = "<script>document.write(screen.width);</script>";
echo $height = "<script>document.write(screen.height);</script>";
?>
I found using CSS inside my html inside my php did the trick for me.
<?php
echo '<h2 media="screen and (max-width: 480px)">';
echo 'My headline';
echo '</h2>';
echo '<h1 media="screen and (min-width: 481px)">';
echo 'My headline';
echo '</h1>';
?>
This will output a smaller sized headline if the screen is 480px or less.
So no need to pass any vars using JS or similar.
You can check it like below:
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
echo "mobile web browser!";
} else {
echo "web browser!";
}
This is a very simple process. Yes, you cannot get the width and height in PHP. It is true that JQuery can provide the screen's width and height. First go to https://github.com/carhartl/jquery-cookie and get jquery.cookie.js. Here is example using php to get the screen width and height:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script type=text/javascript>
function setScreenHWCookie() {
$.cookie('sw',screen.width);
$.cookie('sh',screen.height);
return true;
}
setScreenHWCookie();
</script>
</head>
<body>
<h1>Using jquery.cookie.js to store screen height and width</h1>
<?php
if(isset($_COOKIE['sw'])) { echo "Screen width: ".$_COOKIE['sw']."<br/>";}
if(isset($_COOKIE['sh'])) { echo "Screen height: ".$_COOKIE['sh']."<br/>";}
?>
</body>
</html>
I have a test that you can execute: http://rw-wrd.net/test.php
Use JavaScript (screen.width and screen.height IIRC, but I may be wrong, haven't done JS in a while). PHP cannot do it.
Fully Working Example
I couldn't find an actual working PHP example to "invisibly" (without URL parameters) return client screen size, and other properties, to server-side PHP, so I put this example together.
JS populates and submits a hidden form (scripted by PHP from an array of JS properties), POSTing to itself (the data now available in PHP) and returns the data in a table.
(Tested in "several" browsers.)
<!DOCTYPE html>
<html>
<head>
<title>*Client Info*</title>
<style>table,tr{border:2px solid gold;border-collapse:collapse;}td{padding:5px;}</style>
</head>
<body>
<?php
$clientProps=array('screen.width','screen.height','window.innerWidth','window.innerHeight',
'window.outerWidth','window.outerHeight','screen.colorDepth','screen.pixelDepth');
if(! isset($_POST['screenheight'])){
echo "Loading...<form method='POST' id='data' style='display:none'>";
foreach($clientProps as $p) { //create hidden form
echo "<input type='text' id='".str_replace('.','',$p)."' name='".str_replace('.','',$p)."'>";
}
echo "<input type='submit'></form>";
echo "<script>";
foreach($clientProps as $p) { //populate hidden form with screen/window info
echo "document.getElementById('" . str_replace('.','',$p) . "').value = $p;";
}
echo "document.forms.namedItem('data').submit();"; //submit form
echo "</script>";
}else{
echo "<table>";
foreach($clientProps as $p) { //create output table
echo "<tr><td>".ucwords(str_replace('.',' ',$p)).":</td><td>".$_POST[str_replace('.','',$p)]."</td></tr>";
}
echo "</table>";
}
?>
<script>
window.history.replaceState(null,null); //avoid form warning if user clicks refresh
</script>
</body>
</html>
The returned data is extract'd into variables. For example:
window.innerWidth is returned in $windowinnerWidth
You can try RESS (RESponsive design + Server side components), see this tutorial:
http://www.lukew.com/ff/entry.asp?1392
You can set window width in cookies using JS in front end and you can get it in PHP:
<script type="text/javascript">
document.cookie = 'window_width='+window.innerWidth+'; expires=Fri, 3 Aug 2901 20:47:11 UTC; path=/';
</script>
<?PHP
$_COOKIE['window_width'];
?>
I don't think you can detect the screen size purely with PHP but you can detect the user-agent..
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<link rel="stylesheet" href="/css/mobile.css" />'
}
?>
Here's a link to a more detailed script: PHP Mobile Detect
Here is the Javascript Code: (index.php)
<script>
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/sqldb.php", true);
xhttp.send("screensize=",screen.width,screen.height);
</script>
Here is the PHP Code: (sqldb.php)
$data = $_POST['screensize'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$statement = $pdo->prepare("UPDATE users SET screen= :screen WHERE id = $userid");
$statement->execute(array('screen' => $data));
I hope that you know how to get the $userid from the Session,
and for that you need an Database with the Table called users, and an Table inside users called screen ;=)
Regards KSP
The only way is to use javascript, then get the javascript to post to it to your php(if you really need there res server side). This will however completly fall flat on its face, if they turn javascript off.
JS:
$.ajax({
url: "ajax.php",
type: "POST",
data: "width=" + $("body").width(),
success: function(msg) {
return true;
}
});
ajax.php
if(!empty($_POST['width']))
$width = (int)$_POST['width'];
This can be done easily using cookies. This method allows the page to check the stored cookie values against the screen height and width (or browser view port height and width values), and if they are different it will reset the cookie and reload the page. The code needs to allow for user preferences. If persistant cookies are turned off, use a session cookie. If that doesn't work you have to go with a default setting.
Javascript: Check if height & width cookie set
Javascript: If set, check if screen.height & screen.width (or whatever you want) matches the current value of the cookie
Javascript: If cookie not set or it does not match the current value, then:
a. Javascript: create persistent or session cookie named (e.g.) 'shw' to value of current screen.height & screen.width.
b. Javascript: redirect to SELF using window.location.reload(). When it reloads, it will skip the step 3.
PHP: $_COOKIE['shw'] contains values.
Continue with PHP
E.g., I am using some common cookie functions found on the web. Make sure setCookie returns the correct values.
I put this code immediately after the head tag. Obviously the function should be in a a source file.
<head>
<script src="/include/cookielib.js"></script>
<script type=text/javascript>
function setScreenHWCookie() {
// Function to set persistant (default) or session cookie with screen ht & width
// Returns true if cookie matches screen ht & width or if valid cookie created
// Returns false if cannot create a cookies.
var ok = getCookie( "shw");
var shw_value = screen.height+"px:"+screen.width+"px";
if ( ! ok || ok != shw_value ) {
var expires = 7 // days
var ok = setCookie( "shw", shw_value, expires)
if ( ok == "" ) {
// not possible to set persistent cookie
expires = 0
ok = setCookie( "shw", shw_value, expires)
if ( ok == "" ) return false // not possible to set session cookie
}
window.location.reload();
}
return true;
}
setScreenHWCookie();
</script>
....
<?php
if( isset($_COOKIE["shw"])) {
$hw_values = $_COOKIE["shw"];
}
PHP works only on server side, not on user host. Use JavaScript or jQuery to get this info and send via AJAX or URL (?x=1024&y=640).
The quick answer is no, then you are probably asking why can't I do that with php. OK here is a longer answer. PHP is a serverside scripting language and therefor has nothing to do with the type of a specific client. Then you might ask "why can I then get the browser agent from php?", thats because that information is sent with the initial HTTP headers upon request to the server. So if you want client information that's not sent with the HTTP header you must you a client scripting language like javascript.
For get the width screen or the height screen
1- Create a PHP file (getwidthscreen.php) and write the following commands in it
PHP (getwidthscreen.php)
<div id="widthscreenid"></div>
<script>
document.getElementById("widthscreenid").innerHTML=screen.width;
</script>
2- Get the width screen through a cURL session by the following commands
PHP (main.php)
$ch = curl_init( 'http://hostname/getwidthscreen.php' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec( $ch );
print_r($result);
curl_close( $ch );
Well, I have another idea, thanks to which it is 90% possible in a very simple way using pure PHP. We will not immediately know the exact screen resolution, but we will find out whether the user is using a computer (higher resolution) or a phone (lower resolution) and thanks to this we will be able to load specific data.
Code example:
$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($user_agent, 'Windows') !== false) {
//PC, high resolution
//*note for phone is: Windows Phone
} elseif (strpos($user_agent, 'Mac') !== false) {
//PC, high resolution
} else {
//mobile, small resolution
//Android, iOS, Windows Phone, Blackberry OS, Symbian OS, Bada OS, Firefox OS, WebOS, Tizen OS, KaiOS, Sailfish OS, Ubuntu Touch, HarmonyOS, EMUI, OxygenOS, One UI, Magic UI, ColorOS, MiUI, OxygenOS, ZenUI, LG UX, FunTouch OS, Flyme OS, OxygenOS, Samsung One UI, Android One, Android Go, Android TV, Android Auto, Fuchsia OS.
}
Then, a great solution to complete the verification is to throw a cookie and check the data using PHP.
//JS:
function setCookieResolution() {
// Get screen resolution
if (!getCookieValue("screen_resolution")) {
var screenResolution = window.screen.width + "x" + window.screen.height;
// Create cookie with resolution info
document.cookie = "screen_resolution=" + screenResolution + ";path=/";
}
}
setCookieResolution();
//PHP:
if (isset($_COOKIE["screen_resolution"])) {
$currentValue = $_COOKIE["screen_resolution"];//example: 1920x1080
$parts = explode("x", $currentValue);
if(count($parts) == 2 && is_numeric($parts[0]) && is_numeric($parts[1])) {
$width = (int)$parts[0];
$height = (int)$parts[1];
} else {
// handle error
}
}
In PHP there is no standard way to get this information. However, it is possible if you are using a 3rd party solution. 51Degrees device detector for PHP has the properties you need:
$_51d['ScreenPixelsHeight']
$_51d['ScreenPixelsWidth']
Gives you Width and Height of user's screen in pixels. In order to use these properties you need to download the detector from sourceforge. Then you need to include the following 2 lines in your file/files where it's necessary to detect screen height and width:
<?php
require_once 'path/to/core/51Degrees.php';
require_once 'path/to/core/51Degrees_usage.php';
?>
Where path/to/core is path to 'Core' directory which you downloaded from sourceforge. Finally, to use the properties:
<?php
echo $_51d['ScreenPixelsHeight']; //Output screen height.
echo $_51d['ScreenPixelsWidth']; //Output screen width.
?>
Keep in mind these variables can contain 'Unknown' value some times, when the device could not be identified.
solution: make scalable web design ... ( our should i say proper web design) formating should be done client side and i did wish the info would be passed down to server but the info is still usefull ( how many object per rows kind of deal ) but still web design should be fluid thus each row elements should not be put into tables unless its an actual table ( and the data will scale to it's individual cells) if you use a div you can stack each elements next to each other and your window should "break" the row at the proper spot. ( just need proper css)
<script type="text/javascript">
if(screen.width <= 699){
<?php $screen = 'mobile';?>
}else{
<?php $screen = 'default';?>
}
</script>
<?php echo $screen; ?>

Categories