How can I detect if an iPhone has a retina display or not? Is there a reliable way? Either pure PHP or preferably Zend Framework way of doing this.
i figure it out by this
var retina = window.devicePixelRatio > 1;
if (retina)
{
// the user has a retina display
}
else
{
// the user has a non-retina display
}
You must consider the fact that you are trying to get client side information on the server side.
It would seem that you are unable to detect the display with pure PHP or Zend framework.
It furthermore seems like the UserAgent information from the client, that you might access from PHP is based upon the OS, not the hardware, and thusly does not help you.
You might be interested in reading the following article which much more eloquently and thoroughly explains the issues.
http://www.bdoran.co.uk/2010/07/19/detecting-the-iphone4-and-resolution-with-javascript-or-php/
Good luck!
Javascript: window.devicePixelRatio
I guess as simple thing as display width detection would be sufficient for such a task, retina display packs so many pixels in the width, that simple check will immediately tell you if its an ordinary display or retina display.
PHP does not have such a capability out of a box, but Javascript does.
Here is how :
<script language="Javascript">
<!--
document.write('<br>your resolution is' + screen.width + 'x' + screen.height)
//-->
</script>
Related
I have a small website using only PHP, HTML, and CSS and want to add Dark Mode on it. I've found a lot solutions, but all of them use JavaScript. Is that possible to add Dark Mode without JS?
One option could be to use a routing element in your URL that determines (using server side logic) which set of cascading style sheets gets loaded.
For example in http://foobar.com/dark/path/to/content the /dark/ part of the URL could make the server load your "dark" theme CSS files.
You already have all you need. Browser detection is done with CSS following the Media Queries Level 5 specification using a prefers-color-scheme media query for detection. If you're familiar with responsive web-design with CSS then you already have all the knowledge - the only difference is that responsive CSS is about geography (sizes, columns, padding, spacing, font-size, etc.) and prefers-color-scheme is about ... well ... color. Thomas Steiner (#DenverCoder9) has an awesome article "prefers-color-scheme: Hello darkness, my old friend" that covers this.
If you are asking about PHP specifically then you are out of luck - there is no dark mode detection methodology for server side-processing.
All efforts thus-far by the W3C (and its sponsors) has been focused on client-side / Jamstack.
There is a recommendation by Thomas Steiner (same guy) to implement a Proposed server-side client hint, but this has not been adopted (yet?) by the W3C or the browsers.
Either way - there is a significant drawback in server-side detection (both with Thomas' recommendation and my solution below) in that the server will only know about a state change (e.g. macOS "Auto" mode when night fall happens) on the next server request, or more visibly, the first load of the page.
My recommendation is to leverage CSS / client-side only on this - Thomas gives some practical guidance on two methods,
1x CSS with both color schemes supported, and
2x CSS, with one being light and the other dark. I've made a educative whitepaper applying some of these methods with the CSS framework Bootstrap at vinorodrigues/bootstrap-dark to show how easy that can be - without server-side processing.
Having said that - if you must insist on PHP or server-side detection there is no workaround - but one must use some JS. The most efficient way is to leverage the js-cookie/js-cookie project, and include the following code into your HTML pages:
<script src="https://cdn.jsdelivr.net/npm/js-cookie/dist/js.cookie.min.js"></script>
<script>
// code to set the `color_scheme` cookie
var $color_scheme = Cookies.get("color_scheme");
function get_color_scheme() {
return (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light";
}
function update_color_scheme() {
Cookies.set("color_scheme", get_color_scheme());
}
// read & compare cookie `color-scheme`
if ((typeof $color_scheme === "undefined") || (get_color_scheme() != $color_scheme))
update_color_scheme();
// detect changes and change the cookie
if (window.matchMedia)
window.matchMedia("(prefers-color-scheme: dark)").addListener( update_color_scheme );
</script>
And then your PHP will detect this cookie like this:
$color_scheme = isset($_COOKIE["color_scheme"]) ? $_COOKIE["color_scheme"] : false;
if ($color_scheme === false) $color_scheme = 'light'; // fallback
Which you can use to load the CSS:
// Load the CSS for the correct color-scheme
if ($color_scheme == 'dark') {
?><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/vinorodrigues/bootstrap-dark#0.0/dist/bootstrap-night.min.css"><?php
} else {
?><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0.css/bootstrap.css"><?php
}
Or, like this:
?>You are in <?= $color_scheme ?> mode.<?php
You can do a clone of the css and change the background-color, buttons... It's not really necessary really to use JavaScript
If you want to do just a button for change the css, i don't really know how to do it, but if you want to do another webpage but just for Dark Mode, just put the clone off the css that you created.
I don't know if this is even possible, but I'd appreciate any help.
How do I get the client's DOM width in Laravel?
Basically, is there a way to extract the client's screen width from the $request?
Or are there any functions in Laravel or Blade that will give me a screen width value?
I know that I can get the DOM width with jQuery $(document).width(), but I need the width value on server side; before any js is executed.
#ArturGrigio You can try set JavaScript cookie and access it in Laravel. When user visits your website, get the screen size with JS (window.width) and store it in a cookie screen=WxH
In Laravel $screen = Cookie::get('screen');
$screen = explode("x", $screen);
$width = $screen[0]
$height = $screen[0];
This is 1 solution to do it.
Unfortunately the is no way to get screen size info from PHP.
You can try to play around with User Agent and detect if it is a mobile or desktop or tablet. and make fix sizes for those 3 types.
A good User Agent package for Laravel
I’ve been searching the internet for the past hour, and I didn’t find anything better than hacks and tricks. I didn't even find a good Node.js cross-OS, cross-Browser package to solve this problem...
But to anyone that has a similar question, here is my workaround (even though I still think there might be a better way to achieve the desired outcome, like #Froxz).
Possible Solution:
I used an awesome lazy-load library by Ress.io called LazyLoadXT.
Here is a standard img html tag:
<img src="https://i.stack.imgur.com/5coxi.jpg" width="300px">
Here it is with LazyLoadXT:
<head>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://ressio.github.io/lazy-load-xt/dist/jquery.lazyloadxt.js"></script>
</head>
<img data-src="https://i.stack.imgur.com/5coxi.jpg" width="300px" src="">
And here it is with LazyLoadXT + JavaScript:
<head>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://ressio.github.io/lazy-load-xt/dist/jquery.lazyloadxt.js"></script>
</head>
<script>document.write('<img data-src="https://i.stack.imgur.com/5coxi.jpg" width="' + document.documentElement.clientWidth + 'px" src="">')</script>
This is still ajax (which I was trying to avoid), but it is the cleanest solution I was able to think of.
DEMO: jsFiddle
My objective is printing 10cm x 6.5cm labels for products. I have a Zebra printer for printing labels. I was using Fast-reports for Printing labels by using handheld. Since fast-reports is only for Net Framework and not for Net CF, I was using sockets to handle data between handheld and pc.
Desktop applications hard to make stable for my knowledge of c#. I am a PHP dev. so I thought I can create labels with HTML & CSS since barcodes can also done with php.
The reason I am asking this question because I don't know how to send html page to printer and What sizes should I use for 10cm x 6.5cm with pixels for best quality printing.
Might be a little late for a response but I was facing the exact same problem back in the day and to accomplish what you describe I approached in a weird way that eventually worked. The steps that I describe don't affect the UI but it renders your HTML without the user noticing.
Render the HTML on a Webview that won't be visible to the user and set a WebViewClientCallback that will be called as soon that your WebViewRenders your html.
var webview = new Android.Webkit.WebView(Common.Instance);
webview.Layout(0, 0, widthOfHTML, heightOfHtml);
webview.Settings.LoadWithOverviewMode = true;
webview.Settings.UseWideViewPort = true;
webview.LoadDataWithBaseURL("file:///android_asset/", template, "text/HTML", "UTF-8", null);
webview.SetWebViewClient(new WebViewClientCallback());
In you webviewClient callback override the OnPageFinished method that will
public class WebViewClientCallback : WebViewClient
{
public override async void OnPageFinished(WebView myWebview, string url)
{
// Render webview to a bitmap
var bitmap = Bitmap.CreateBitmap(myWebview.Width, myWebview.Height + 50, Bitmap.Config.Argb8888);
// Code to print bitmap
}
}
You will need to set up a #media print { YOUR CSS STYLES } after you get that set the way you want it to look when printed. Make sure to convert your cm to one of these as well pt, px, em or rem. You can then add a bit of javascript to a button to make it open in print view if you want otherwise you would just right-click on the html page and tell it to print. Using the javascript something like this:
<button onclick="myFunction()">Print this page</button>
<script>
function myFunction() {
window.print();
}
</script>
I read about Masonry and after failing to get image appending to work was advised to switch to the successor Isotope. I was trying to improve or create variations on an album cover gallery, something I've done once or twice before using the same PHP classes.
I can get the basic functionality to work, but a button to click to add more images has always failed to work. I keep reading jQuery documentation and I've tried various JavaScript debuggers but I always end up with no images being added to my gallery when I click.
Trial and error is definitely required to get the best looking layout.
The biggest album cover seems to be 500 pixels with the smallest found in APIs was 75, choosing the right column width helps. I'm currently using 75 but 50 might have worked better. I just want to get adding images to work and be done with this little experiment.
I wanted to try something similar to this technique of appending more images to the bottom. I want to append more album covers which I fetch from various APIs (Amazon Product API, Last.fm, iTunes) using PHP. All the album covers come from APIs and I use PHP to find the URLs given the album title and artist. My code is running: http://www.muschamp.ca/Muskie/cdCoverGalleryV4.php
I've changed the CSS rule many times, now I just have the default CSS suggested by the Isotope author.
PHP Code that loops and produces 10 divs with one image per div
$myAlbumCollection->randomMember();
$count = 0;
print('<div id="container">');
while ( $count < 10 )
{
// Check that current album is in Amazon
$buyLink = $myAlbumCollection->currentAlbumAmazonProductURL();
$imageURL = $myAlbumCollection->currentAlbumRandomImageURL();
if ( (strcmp($buyLink, '#') != 0) && (strcmp($imageURL, myInfo::MISSING_COVER_URL) != 0))
{
$count++;
print('<div class="item">');
print('<a href="' . $buyLink . '">');
print('<img src="' . $imageURL . '" />');
print('</a>');
print('</div>');
}
$myAlbumCollection->goToNextAlbum(); // This could loop forever if it doesn't find enough album covers, but in reality will timeout
}
print('</div>');
And lastly here is the javascript, the final problem is in here somewhere:
<script>
$(function(){
var $container = $('#container');
$('#insert a').click(function(){
var $newEls = $.get('./moreAlbumCovers.php');
$container.isotope( 'insert', $newEls );
return false;
});
$container.isotope({
itemSelector: '.item',
masonry: {
columnWidth: 75
}
});
});
</script>
The link gets called when clicked, I've stepped through it. The PHP produces DIVs As and IMG tags. I really am not sure what I'm doing wrong and repeated readings of the documentation isn't solving it. I've never really been a JavaScript guy. I'm not even a PHP guy, it seems right but repeated efforts to make it go have failed despite generous assistance and offering a bounty.
Thanks for the help.
Try adjusting the columnWidh value and width of item. Masonry aligns element with best fit column first layout. It works on mathematical equations. So a perfect, brick wall fitting is only hypothetical ideal case. It takes me a few tries on firebug and other tools to get the masonry working with ideally fitted layout. The key is to get the value of columnWidth and width, gutter etc in such a way that it solves the logic equations in good values.
:: EDIT ::
I found a link saved in my pockets page, of which i totally forgot about. It is a great tutorial. So i came back to give it here. Recommended to everyone who have trouble getting started with this plugin.
http://www.netmagazine.com/tutorials/get-started-jquery-masonry
Masonry isn't a very descriptive name for it. In fact it's an optimizing problem. It's something that is called np problem because there is too many permutations to check. Especially the masonry jquery plugin is a 1d bin-packing solver and it's arrange the bricks in vertical columns. Css by default arrange the bricks in horizontal order. In other words it's a depth-first sort of an adjacent tree model.
Update: Try adding masonry to your dummy div and delete everthing else:
$('#dummy').load('./moreAlbumCovers.php').masonry("reload");
I think you overthink it. The variable is empty because you assign it to a dom object. It's most likely become also an object and not usefull.
It's relly well explained here Jquery Masonry Seamless Responsive Image Grid + I would try to do exactly the same with isotope http://isotope.metafizzy.co/
edit:
I think isoptope and masonry just sorting out 1 dimensional bin packing, and what you are maybe looking after is 2 dimensional bin packing
like this http://codeincomplete.com/posts/2011/5/7/bin_packing/example/ (check complex case it fits all boxes perfectly )
and lib for that https://github.com/jakesgordon/bin-packing/
To get the more brick wall like effect you don't set an item width using CSS. This wasn't crystal clear given the instructions here. But a lot of testing seems to indicate that just specifying a columnWidth and then letting the browser and javascript do it's best gets closer to the performance I'm looking for. Will have to tweak and eventually try appending...
Hi I want to detect ipad orientation in php, i know i can detect the iPad but how do i detect the orientation, i need it in php and not css because i want to show x pictures in my gallery in portrait and x in landscape.
here is the code i am using to detect the php for iPad:
if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') !== FALSE) {
} else {
}
i have checked on this site and on google but was unable to find anything which could help
thankyou
iPad orientation can change when the user holds her iPad differently. Therefore, there's no point of registering it in php - by the time your response reaches the client, it might already be different.
If there needs to be any plumbing that can't be done in CSS (like loading different images or so), handle the orientationchanged event in JavaScript.
This is not orientation detection but USER AGENT detection. It only detects what kind of browser is browsing your page.
Are you trying to detect the device or what way the device is rotated?
I believe you would have an easier time detecting the orientation of a device either in Javascript or CSS, have you looked into these yet?
Javascript:
<button onclick="detectIPadOrientation();">What's my Orientation?</button>
<script type="text/javascript">
window.onorientationchange = detectIPadOrientation;
function detectIPadOrientation ()
{
if ( orientation == 0 ) {
alert ('Portrait Mode, Home Button bottom');
}
else if ( orientation == 90 ) {
alert ('Landscape Mode, Home Button right');
}
else if ( orientation == -90 ) {
alert ('Landscape Mode, Home Button left');
}
else if ( orientation == 180 ) {
alert ('Portrait Mode, Home Button top');
}
}
</script>
CSS
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
The device orientation is dynamic - the user can rotate the device after the page has been loaded. Therefore, it makes no sense to include it in the user agent string.
Instead, you should use HTML and JavaScript to change the layout when the orientation changes.
Everyone is suggesting you do it in Java Script which is completely correct but I'm guessing you don't see that as an option from your question.
You should load enough images (or all if not a stupid number, it is only a URL string after all) from PHP to fill the largest size in JSON (json_encode($array of image URL's to use)) format. Then use JavaScript to detect orientation and populate the page with the correct number/layout of images.
You'll have an array in JavaScript of Image URL's to pick from and load dynamically.
use this code may be use full to you
var orient = Math.abs(window.orientation) === 90 ? 'landscape' : 'portrait';
A brutal way would be to store the orientation change in a cookie through jQuery and access it with the $_COOKIE variable in php.
However, you would still need the javascript hooks to detect the orientation change and possibly a page reload.