How can I make my CAPTCHA script have a refresh link? - php

I have a captcha script and it works good. But, I don't know how to make it refresh.
Here's verificationimage.php:
<?php
header('Content-type: image/jpeg');
$width = 50;
$height = 24;
$my_image = imagecreatetruecolor($width, $height);
imagefill($my_image, 0, 0, 0xFFFFFF);
// add noise
for ($c = 0; $c < 40; $c++){
$x = rand(0,$width-1);
$y = rand(0,$height-1);
imagesetpixel($my_image, $x, $y, 0x000000);
}
$x = rand(1,10);
$y = rand(1,10);
$rand_string = rand(1000,9999);
imagestring($my_image, 5, $x, $y, $rand_string, 0x000000);
setcookie('tntcon',(md5($rand_string).'a4xn'));
imagejpeg($my_image);
imagedestroy($my_image);
?>
And, the page with the form:
<label for="verif_box" style="margin-top:10px;">Image Verification:</label>
<input name="verif_box" type="text" id="verif_box" autocomplete="off" minlength="4" maxlength="5" class="text" />
<img id="captcha" src="verificationimage.php?<?php echo rand(0,9999);?>" alt="This form can't be submitted because images aren't displayed" title="Verification image, type it in the box" width="50" height="24" align="absbottom" onclick="$('#verif_box').focus();" style="cursor:pointer;" /> (what's this?)
<br />
<br />
<?php
//if the variable "wrong_code" is sent from previous page then display the error field
if(isset($_GET['wrong_code'])){?>
<div style="border:1px solid #990000; background-color:#D70000; color:#FFFFFF; padding:4px; padding-left:6px;width:295px;">The code you entered does not match the image. Please try typing what you see in the image to the right again.</div><br />
<?php ;} ?>
Here is what happens in mailer.php:
// check to see if verificaton code was correct
if(md5($verif_box).'a4xn' == $_COOKIE['tntcon']){
// if verification code was correct send the message and show this page
mail("email#domain.com", 'New WeeBuild Support Ticket: '.$subject, $emailContent, $headers);
mail($email, 'Thank you for contacting WeeBuild Support! (#'.$ticket.')', $emailContents, $headers2);
// add to database
$today = getdate();
$theDate = $today["weekday"].", ".$today["month"]." ".$today["mday"].", ".$today["year"];
mysql_select_db("database_name", $con);
$sql="INSERT INTO table_name (name, email, subject, message, ticket, ip_address, created)
VALUES ('$_POST[name]','$_POST[email]','$_POST[subject]','$_POST[message]','$ticket','$_SERVER[REMOTE_ADDR]','$theDate')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
//close the database connection
mysql_close($con);
// delete the cookie so it cannot sent again by refreshing this page
setcookie('tntcon','');
} else if(isset($message) and $message!=""){
// if verification code was incorrect then return to contact page and show error
header("Location: index.php?name=$name&subject=$subject&email=".urlencode($email)."&message=".urlencode($message)."&wrong_code=true");
exit;
}
It all currently works great, but how can I make the captcha refresh? I tried doing this:
<script>
$(document).ready(function() {
$('#refresh').click(function() {
$('img#captcha').attr('src','verificationimage.php?<?php echo rand(0,9999);?>');
});
});
</script>
refresh
But, it doesn't work.
By the way, I don't want to use reCaptcha, I just rather do it this way because reCaptcha, to me, looks hard to set up with my stuff.

My answer is similar to the one in the comments, likely a cached copy is being used on the refresh, but it'd be cleaner to use a proper method to make sure the browser doesn't cache that image rather than a random string. On the image generation page, add this:
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

Since the image tag has an id, that's the only thing you'll need for the selector.
I think the problem comes from browser caching : because the random string is generated by PHP the refresh button will work only once (since the next calls will use the same string, the browser will use the cached version instead).
This should do the trick, a new random string is generated everytime the button is pressed :
$(function() {
$('#refresh').click(function() {
$('#captcha').attr('src', 'verificationimage.php?' + new Date().getTime());
return false;
});
});

There are better, more secure ways to send the CAPTCHA information for verification besides using a cookie. At the very least, I would suggest using a session variable, but with a named session and IP verification, to prevent session hijacking. It would also be a VERY good idea to add hotlinking prevention to your CAPTCHA image generation script, so that someone can't just pull up the CAPTCHA image in a browser, all by itself. just a suggestion. :)
In order to use hotlink prevention, just add the following code to the top of the image creation script:
if (!isset($_SERVER['HTTP_REFERER']) or checkValidReferer() === false) die();
function checkValidReferer() {
$out = false;
$ref = $_SERVER['HTTP_REFERER'];
$lh = $_SERVER['HTTP_HOST'];
if (stripos($ref,$lh) !== false) $out = true;
return $out;
}
The above code outputs a good image, if the base URL of the referrer both exists, and is identical to the base URL of the image script. This prevents the image from being used somewhere other than where it's supposed to.

Related

how to clear cache using PHP?

how could I clear the cache for the image instantly with my uploader? I'm currently trying this but isn't working. any suggestion? thank you !
ps : settings.php is the current page, and I'm using only one header location
the image is currently uploader some time, but not always, some time it doesn't work without a ctrl + maj + r
uploader code :
<?php
// UPLOAD FICHIER
if (isset($_POST['valider']))
{
if (isset($_FILES['avatar']) AND !empty($_FILES['avatar']['name']))
{
$tailleMax = 1000000;
$extensionsValide = array('jpg', 'png');
if ($_FILES['avatar']['size'] < $tailleMax)
{
$extensionsUpload = strtolower(substr(strrchr($_FILES['avatar']['name'], '.'), 1));
if (in_array($extensionsUpload, $extensionsValide))
{
$chemin = "../images/avatar/" . $_SESSION['id'] . "." . $extensionsUpload;
$resultat = move_uploaded_file($_FILES['avatar']['tmp_name'], $chemin);
$touxiang = $_SESSION['id'] . "." . $extensionsUpload;
$session = $_SESSION['id'];
if ($resultat)
{
$updateAvatar=$dbh->prepare("UPDATE members SET avatar = :avatar WHERE id = :id");
$updateAvatar->bindValue('avatar', $touxiang);
$updateAvatar->bindValue('id', $session);
$updateAvatar->execute();
header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');
header('Location: settings');
}
else
{
echo "<p class='review_wrong'>error.</p>";
}
}
else
{
echo "<p class='review_wrong'>wrong format. jpeg png.</p>";
}
}
else
{
echo "<p class='review_wrong'>File too large.</p>";
}
} // ISSET
}
?>
<div id="avatar_send_div">
<input id="upload_header" type="file" name="avatar">
<label for="upload_header" class="btn">Upload</label>
<input id="submit_header" type="submit" name="valider" value="Validate">
</div>
show image :
<?php
if (isset($_SESSION['id']) AND !empty($_SESSION['id']))
{
$id = $_SESSION['id'];
$req = $dbh->prepare('SELECT * FROM members WHERE id = :id');
$req->bindValue('id', $id);
$req->execute();
$userinfo = $req->fetch();
}
?>
<div id="settings_div_img">
<img id="settings_img" src="../images/avatar/<?php echo $userinfo['avatar'];?>">
</div>
db :
As others have stated in the comments, you can't really clear the cache with PHP, certainly not the cached assets (images, CSS files, etc). Assets are almost all the time served directly by the webserver.
The HTTP headers that you are setting with PHP will only affect the document being returned by your PHP script, which in your case is an HTML page. Also, sending headers does not guarantee that the cached document will be cleared (it's the job of the user's browser to do that).
So you are generating an HTML page with URLs pointing to images served by the webserver. To control the cache of these images, you mostly want to configure the webserver itself (Apache, NGINX, etc)
That again won't necessarily work if the user already has a previously cached image.
A common technique to go around that and avoid having to generate new image filenames is to append a version id to the image URL and change it as new versions of the image are uploaded.
So instead of having example.net/john.png you would generate example.net/john.png?v=1 and then when you upload a new image, you generate a new URL example.net/john.png?v=2. You can basically append anything to the query string, the goal is to generate a new URL that the browser hasn't seen before.
You will find more techniques here: Refresh image with a new one at the same url
I hope that helps.

Why php session is not a value but blank in my login page

In my project, i have a login page with verification code.
Some verification code of login page is like:
<form class="form-login" action="index.php" method="post">
<input type="text" name="code" class="form-control" placeholder="verification code">
<img id="codeImg" src="create_code.php" alt="not clear, another" style="cursor: pointer; vertical-align:middle" onClick="create_code()">
</form>
In create_code.php, some code about creating verification code is like:
session_start();
header("Content-type: image/png");
$str = "1,2,3,4,5,6,7,8,9,a,b,c,d,f,g";
$list = explode(",", $str);
$cmax = count($list) - 1;
$verifyCode = '';
for ( $i=0; $i < 5; $i++ ){
$randnum = mt_rand(0, $cmax);
$verifyCode .= $list[$randnum];
}
$_SESSION['code'] = $verifyCode; // stor verifycode in session
In index.php, I need to check the inpu verifycode and session verifycode, some code is like:
session_start();
if(!isset($_GET['log_out']) && ($_POST['code'] != $_SESSION['code']))
{
echo "verifycode is wrong!<br />" . "<meta http-equiv='refresh' content='2;url=index.html'>";
die();
}
But unlucky, it is fail. I have found there is nothing in $_SESSION['code']。$_SESSION['code'] should be a value, but a blank instead.
besides, it worked OK a few days ago, but it fails today. I have no changed any code, it seems nothing wrong, who can help me ?
I have solved this problem。 My Linux server disk space is 100%. When I deleted some files, it works Ok. Is there some session log file can print prompt message ?

Is it only by submitting the form that the session captcha can be get?

I want to get the session captcha value in the onsubmit event of the form , so if the text entered is different of the session captcha data then I will cancel form submission. The problem is that I cannot get the session captcha value on document ready :
file of the captcha generation is named securitecode.php :
<?php
session_start();
$largeur = 120;
$hauteur = 40;
$longueur = 5;
$liste = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$code = '';
$counter = 0;
$image = #imagecreate($largeur, $hauteur) or die('Impossible d\'initializer GD')
;
for( $i=0; $i<10; $i++ ) {
imageline($image,
mt_rand(0,$largeur), mt_rand(0,$hauteur),
mt_rand(0,$largeur), mt_rand(0,$hauteur),
imagecolorallocate($image, mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)
));
}
for( $i=0, $x=0; $i<$longueur; $i++ ) {
$charactere = substr($liste, rand(0, strlen($liste)-1), 1);
$x += 10 + mt_rand(0,10);
imagechar($image, mt_rand(3,5), $x, mt_rand(5,20), $charactere,
imagecolorallocate($image, mt_rand(0,155), mt_rand(0,155), mt_rand(0,155)));
$code .= $charactere;
}
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
$_SESSION['securecode'] = $code;
?>
In my web page I create the image captcha :
...
<img id="captcha_img" src="securitecode.php" />
<input type="text" id="captcha" />
<span id="msg_captcha"></span>
...
<script type="text/javascript">
$(document).ready(function() {
$('#msg_captcha').html("<?php echo $_SESSION['securecode']; ?>");
});
</script>
When the page loads for the first time there is nothing displayed inside the #msg_captcha span ! So how to get the captcha session data ?
This is because of the way sessions work.
Session values is available when a session is over and the session data has been written to the session file.
When requesting the page, you actually try to obtain a session value that hasn't yet been set for two reasons.
The captcha image is loaded AFTER your initial request, but PHP has already handled the <?php echo $_SESSION['securecode']; ?> part.
The $_SESSION['securecode'] value is written after the image has been loaded.
So basically, your solution is trying to read values too early.
The solution?
Check the captcha code with AJAX or verify the captcha code on the next request.
Javascript can't run PHP that way.
PHP is a server side language, javascript is client side.
Maybe this topic can help you.

Serving download after form submit w/ validation

I have created together a pretty simple Download Code redeemer in .php (thanks to help from here) and am having a hard time trying to figure out what the best way to serve a download is if the validation is successful. Basically -
User enters invalid code -> Page is refreshed with error message.
User enters valid code -> Give download 'Save as' -> refresh page.
At the minute I'm using http://www.zubrag.com/scripts/download.php to serve the file but once it has started downloading, my form refreshes the page but only half loads the content?!
This is the form with the PHP script I did.
<div class="dcrForm">
<p>Have a physical copy of this release? Claim your digital download by entering your Download Code below.</p>
<form action="index.php" method="post">
<input type="text" name="code" class="dcrInput" value="">
<input type="submit" name="harrisSubmit" class="dcrSubmit" value="Submit">
</form>
<?php
include("scripts/dcr_config.php");
$code="";
$log="";
if (isset($_POST['harrisSubmit']))
{
$code=$_POST['code'];
$link = mysql_connect($hostname, $dbusername, $dbpassword);
mysql_select_db("$databasename");
$query = "select count from $harris where code='$code'";
if ($q=mysql_query($query))
if ($r=mysql_fetch_array($q)){
if ($r[0]<3)
{
$subquery="update $tbname set count='".($r[0]+1)."' where code='$code'";
mysql_query($subquery);
?><script>window.location.href="download.php?f=test.txt";</script><?php
}
}
$log="<p>Invalid code. Try Again.</p>";
}
echo $log."";
?>
</div>
Does anyone have an ideas on what the best way to serve the download would be? I know that currently anyone who had the file location could download the file but I'm not sure how I could go about protecting i
I am glad you have made it this far!
If you are going to redirect the user to a download script, that script would need to have some sort of token attached to it as to prevent unauthorized downloads, basically re-verifying the code or token given.
In the above script, instead of outputting the javascript to redirect to the download script you could do this:
<?php
include "scripts/dcr_config.php";
$code = "";
$log = "";
if (isset($_POST['harrisSubmit'])) {
$code = trim($_POST['code']);
$link = mysql_connect ( $hostname, $dbusername, $dbpassword );
mysql_select_db ( "$databasename" );
$code = mysql_real_escape_string($code); // very important! protects against exploits
$query = "select count from $harris where code='$code'";
if ($q = mysql_query ( $query )) {
if ($r = mysql_fetch_array ( $q )) {
if ($r [0] < 3) {
$subquery = "update $tbname set count='" . ($r [0] + 1) . "' where code='$code'";
mysql_query ( $subquery );
$file = '/path/to/protecteddownload.txt';
// send file to browser as a download dialog
// no content can be output prior to these header() calls
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.txt"');
header('Content-Length: ' . filesize($file));
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
echo file_get_contents($file);
exit; // terminate script
} else {
$log = 'Sorry, this code has already been redeemed.';
}
} else {
$log = 'Invalid download code. Try again.';
}
} else {
// query failed
$log = 'An error occurred validating your code, please try again later.';
}
$log = "<p>Invalid code. Try Again.</p>";
}
?>
<?php if (isset($log) && $log != ''): ?>
<strong class="error"><?php echo $log ?></strong>
<?php endif; ?>
<div class="dcrForm">
<p>Have a physical copy of this release? Claim your digital download by
entering your Download Code below.</p>
<form action="index.php" method="post"><input type="text" name="code"
class="dcrInput" value=""> <input type="submit" name="harrisSubmit"
class="dcrSubmit" value="Submit"></form>
</div>
The download script is probably similar to some of what I have above.
The key thing about this example is that the file you are serving with file_get_contents, is not accessible from the web. You only send it when a valid code is entered.
I have just 1 quick question, how big is this file? Could this be a case that the php timeout is being experienced while reading the file to the browser?
You could play around with the php settings to confirm this (http://php.net/manual/en/function.set-time-limit.php).
Just my 2 cents

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