Issue with Cookie Values being read correctly - php - php

Am trying to set the path for an image to be changed according to a php variable that gets determined by reading a cookie for window.innerWidth ( which is set in the head of the file)
The problem is that the cookie is not being read correctly on the first render by the browser, i have to refresh the browser x 2 to get the correct image.
Could anybody point me in the right direction please ? is there a method in php to get the cookie to always be read correctly the first time - at present it looks like it is being cached, or something like that.
Thank you
Example here : http://markaprice.co.uk/2012dev/r-img-set/image-test-ht.php
html below:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>document.cookie = "device_dimensions=" + window.innerWidth;</script>
<link rel="stylesheet" type="text/css" href="css/img-styles.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<?php require_once('deliver-images.php'); ?>
<img class="ri" src="<?php echo $imgPath ?>the-landscape.jpg" alt="the landscape">
<img class="ri" src="<?php echo $imgPath ?>the-landscape-b.jpg" alt="the landscape">
php script(deliver-images.php) is below:
<?php
$device_width = 0;
$imgPath='';
// Read the device viewport dimensions
if (isset($_COOKIE['device_dimensions'])) {
$device_width = $_COOKIE['device_dimensions'];
echo($device_width);
}
if ($device_width > 0) {
// Low resolution image
if ($device_width <= 480) {
$imgPath = 'images/mobile/';
}
// Medium resolution image
else if ($device_width <= 1024 && $device_width > 480) {
$imgPath = 'images/tablet/';
}
else {
$imgPath = 'images/desktop/';
}
} else {
$imgPath = 'images/desktop/';
}
?>

This following line of yours sets the cookie.
<script>document.cookie = "device_dimensions=" + window.innerWidth;</script>
And this php file is where you check this cookie to make the decision about from which folder you are going to serve images.
<?php require_once('deliver-images.php'); ?>
Looking at your code it seems like you are thinking it that way.
First your script tag run and cookie got set
And then your PHP who use that cookie set in previous step to do some precessing
But that's wrong PHP is processed first on the server and then that page is sent to browser and your script runs.
Conclusion : First time when you open the page your cookies were not set because the script will run after the php code runs.

Related

Return to original page after PHP script send video

Is there a way to jump back to original page after video has finished playing?
I call PHP from link to video in HTML
...
<a href="play.php">My Video
...
and play.php sends back video
like this:
<?php
$CTYP= 'video/mp4';
$VidPath = "../MyVideo.mp4";
header('Content-Type: ' . $CTYP);
$VidFl = fopen($VidPath, "rb");
$VidContent = fread($VidFl, filesize($VidPath));
fclose($VidFl);
echo $VidContent;
?>
Thanks
Final update for anyone who has a similar problem, It is now working version with original approach modified based on suggestions (should've probably read more carefully to avoid running around the solution:).
so index.html with <video> tags
....
<tr><td>
<video height="auto" width="200" controls >
<source src="play.php?play_video=101" type="video/mp4">
</video>
</td> <td>Lecture 101....</td>
</tr><tr><td>
<video height="auto" width="200" controls >
<source src="play.php?play_video=102" type="video/mp4">
</video>
</td> <td>Lecture 102....</td>
</tr>
....
and play.php return stream like originally to href link tag
<?php
include 'dblog.php';
if ( ($_SERVER['REQUEST_METHOD'] === "GET")
&& ( isset($_GET['play_video']) ) ) {
if ($_GET['play_video'] == "101") {
$file_path_name = "../../DVD/Lecture-101.mp4";
} elseif ($_GET['play_video'] == "102") {
$file_path_name = "../../DVD/Lecture-102.mp4";
}
$ctype= 'video/mp4';
header('Content-Type: ' . $ctype);
$handle = fopen($file_path_name, "rb");
$contents = fread($handle, filesize($file_path_name));
fclose($handle);
write_vid_log($_GET['play_video'], $DB, 'start');
echo $contents;
} else {
echo "alert(I'm Sorry wrong link)";
}
?>
So now works to be able to supply links outside of www root folder, and it plays video when client clicks. A few more challenges:
links to media files are easy downloadable, even though path, and file name is not shown, so I need use PHP script to check user and his rights before streaming video file
use CSS to resize and center video over the page, once clicked to play, and can be made seen as if it's playing in the lightbox. Looks like this is possible even without any JS
Any extra suggestions, would be appreciated
An update, to a partial solution based on the feedback I received, I updated php script to send back <video> tag and open new page, with event (vid.onend) to go to previous page after video ends.
So to anyone with similar problem here is updated code
index.html has
...
<a href="play.php">My Video
...
and my play.php file is like this
<?php
$VidPath = "../MyVideo.mp4";
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<link rel="stylesheet" href="video.css" media="screen,print" />'
<title>Test Video play list</title>
<meta charset="utf-8" />
</head>
<body>
<video id="MyVideo" height="auto" width="auto" controls autoplay > <source src=<?php echo $VidPath; ?> type="video/mp4"> </video>
<script>
var vid = document.getElementById("MyVideo");
vid.onended = function() {
history.back();
};
</script>
</body>
</html>
This is a good option to:
play video in empty page and style it with CSS so can look practically like lightbox without any JS or outside code
after video ends, I can automatically jump back to original list
But still can't:
specify path outside of root folder of the website
firefox seems not want to do autoplay, so extra click is necessary
play video in same page as my index.html that would look like lightbox efect
Hope for some more tips
D

Lines from a file as variables

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>squared.php</title>
<link href="/library/skin/tool_base.css" type="text/css" rel="stylesheet" media="all" />
<link href="/library/skin/durham/tool.css" type="text/css" rel="stylesheet" media="all" />
<script type="text/javascript" src="/library/js/headscripts.js"></script>
<style>body { padding: 5px !important; }</style>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<title>Squared</title>
<link rel ="stylesheet" type="text/css" href="sample.css">
<h1> Squared </h1>
</head>
<?php
//Save the three values from the file
$beginningNum = $_POST['beginningNum'];
$endingNum = $_POST['endingNum'];
$incrementer = $_POST['incrementer'];
//Open the file and read the numbers
$dataFilePointer = fopen("output.txt", "r");
$beginningNum = fgets($dataFilePointer);
$endingNum = fgets($dataFilePointer);
$incrementer = fgets($dataFilePointer);
fclose($dataFilePointer);
// Loop through beginning with beginningNum until you get to endingNum and increment by incrementer
// The first statement says "Start x at the entered beginningNum
// The second statement says "Loop until $x gets to the endingNum value
// The third statement says "Increment $x by the incrementer after every loop (also known as counter)
// Check to make sure each value is a numeric then do the for loop, if not - print an error message
if (is_numeric($beginningNum) and is_numeric($endingNum) and is_numeric($incrementer)) {
for ($x = $beginningNum; $x <= $endingNum; $x += $incrementer) {
//Square $x for every increment of it using pow
$squaredNum = pow($x, 2);
// Print $squaredNum to the user
print("<p> The Final Results are $squaredNum.</p>");
}
} else {
print("<p>Error.</p>");
print("Return to Form.");
}
?>
This is what I have so far. I want to write a squared.php file that receives a filename from squared.html. It should read three values from that file:
The first line in the file will contain the starting value
The second line in the file will contain the ending value
The third line in the file will contain the value by which the counter is updated (often increments, but not always)
** Wait for instruction on Wednesday about this:
Read these 3 values, and confirm that they are numeric values using the `php` function `is_numeric()`.
If not, display an error message and offer the user a link to return to the `HTML`.
If it is valid input, your code should contain the following logic:
Use a for loop that will use the start, ending, and update values to display the those values squared.
For example, if a user enters: (I will test your code with other values)
Start Value: 5
End Value: 20
Increment: 5
Your results should be:
5 squared is 25
10 squared is 100
15 squared is 225
20 squared is 400

print_r causes page to refresh?

This is very bizarre and I have spent quite a while trying to figure out why the pages I was testing kept refreshing when they weren't supposed to. I finally narrowed it down to when I deleted the print_r($_SESSION['boosters']) code it quit refreshing. When the print_r is there it refreshes. You can test this yourself at http://prayerpond.com/posttest2.php (just keep manually refreshing the page and look at the counter).
Take a look at the counter displayed at the beginning of the page. If it skips a number then it is refreshing the page once it gets to the print_r.
Here's the code for the counter at the beginning of the page:
$_SESSION['counter']++;
echo $_SESSION['counter'];
Here's the rest of the code (I deleted everything else that was unnecessary to recreate the problem):
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/start.php");
// PRE-HEADER PROCESSING
unset($_SESSION['boosters']);
$_SESSION['counter']++;
echo $_SESSION['counter'];
$sql = "SELECT prayers_views_likes.*, prayers.postid, prayers.privacy, prayers.username
FROM prayers_views_likes
LEFT JOIN prayers ON prayers_views_likes.postid = prayers.postid
WHERE prayers_views_likes.type = 'answer'
and prayers.privacy != 'hidden'
and prayers.username != 'hoodleehoo'
and prayers_views_likes.adj_ratio > 0
ORDER BY prayers_views_likes.adj_ratio DESC, prayers_views_likes.views DESC
";
$_SESSION['boosters'] = send_query($sql);
print_r ($_SESSION['boosters']); //DELETE
// END PRE-HEADER PROCESSING
?>
<!doctype html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
</head>
<body>
</body>
</html>
This is driving me NUTS! Anyone know what on earth is causing this?
Try doing:
echo '<pre>' . htmlentities(print_r($_SESSION['boosters'], true)) . '</pre>';
Giving a true second argument to print_r() makes it return the formatted string instead of outputting it directly. Then htmlentities() will encode any HTML syntax in the result -- there's probably some HTML or Javascript that's causing the refresh. I also put it inside <pre> so that the formatting will be retained.

Ajax save function to server doesn't work correctly

I'm working on a website that let's users simply save a note, to be accessed later. I'm however having quite some trouble with actually saving the note. I first had it set to automatically save on each keypress, but it's better if I have the user press on a button to save the file. What you'll also see in the code is that the note gets saved as the users IP address, when the user then visits the site again he'll see the same note (if he has the same IP again).
The error I get now when clicking the save button is:
PHP Warning: file_put_contents() [<a href='function.file-put-contents'>function.file-put-contents</a>]: Filename cannot be empty in /home/martmart/public_html/index.php on line 41
My index.php:
<?php
$note_name = 'note.txt';
$uniqueNotePerIP = true;
if($uniqueNotePerIP){
// Use the user's IP as the name of the note.
// This is useful when you have many people
// using the app simultaneously.
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$note_name = 'notes/'.$_SERVER['HTTP_X_FORWARDED_FOR'].'.txt';
}
else{
$note_name = 'notes/'.$_SERVER['REMOTE_ADDR'].'.txt';
}
}
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
// This is an AJAX request
if(isset($_POST['note'])){
// Write the file to disk
file_put_contents($note_name, $_POST['note']);
echo '{"saved":1}';
}
exit;
}
$note_content = 'Write something here :D';
if(file_exists($note_name) ){
$note_content = htmlspecialchars( file_get_contents($note_name) );
}
function saveNow() {
// Write the file to disk
file_put_contents($note_name, $_GET['note']);
echo '{"saved":1}';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Marty Testweb</title>
<!-- Our stylesheet -->
<link rel="stylesheet" href="assets/css/styles.css" />
<!-- A custom google handwriting font -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Courgette" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="assets/audiojs/audio.min.js"></script>
<script>
audiojs.events.ready(function() {
var as = audiojs.createAll();
});
</script>
</head>
<body>
<div id="pad">
<h2>Note</h2>
<textarea id="note"><?php echo $note_content ?></textarea>
</div>
<!-- Initialise scripts. -->
<script>
function saveNow()
{
alert("<?php saveNow(); ?>");
}
</script>
<button id="save" onclick="saveNow()">Save Note</button>
<!-- JavaScript includes. -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="assets/js/script.js"></script>
</body>
<div id="footer">
<footer>
<a href="">
<div id="footer_right">
Version 0.1.2
</div id="footer_right">
</a>
<audio src="assets/audiojs/music.mp3" preload="auto"></audio>
<div id="footer_left">
Save function not working yet
</div id="footer_left">
</footer>
</div id="footer">
</html>
The script.js:
$(function(){
var note = $('#note');
var saveTimer,
lineHeight = parseInt(note.css('line-height')),
minHeight = parseInt(note.css('min-height')),
lastHeight = minHeight,
newHeight = 0,
newLines = 0;
var countLinesRegex = new RegExp('\n','g');
// The input event is triggered on key press-es,
// cut/paste and even on undo/redo.
note.on('input',function(e){
// Count the number of new lines
newLines = note.val().match(countLinesRegex);
if(!newLines){
newLines = [];
}
// Increase the height of the note (if needed)
newHeight = Math.max((newLines.length + 1)*lineHeight, minHeight);
// This will increase/decrease the height only once per change
if(newHeight != lastHeight){
note.height(newHeight);
lastHeight = newHeight;
}
}).trigger('input'); // This line will resize the note on page load
function ajaxSaveNote(){
// Trigger an AJAX POST request to save the note
$.post('index.php', { 'note' : note.val() });
}
});
I don't really know how to solve this, so any help is greatly appreciated. I just want to have the file save with the same name as the user's IP address, when he click on the button. Please keep in mind I'm still a big newbie with these more advanced features so please point out anything I did wrong (but also please explain it easy :) ).
Thanks for reading,
Mart.
First of all I would suggest considering whether having the filename be the IP address is a good idea...many workplaces and other group settings share the same IP address, so any user at a workplace like that would see the note left by any other user at the same workplace.
As to your error, I think the problem may be that you didn't declare $note_name as a global variable within your function. Try changing it to this:
function saveNow() {
global $note_name;
// Write the file to disk
file_put_contents($note_name, $_GET['note']);
echo '{"saved":1}';
}
In PHP if you want to use a global variable (one that wasn't declared inside a function or class) within a function, you always have to use the global keyword as shown above. Using global variables can be avoided entirely if you structure your code a bit differently, but that's another topic.
I wonder why you didn't get a notice about it not being defined though...while you're still developing you might want to put this at the top of your code:
error_reporting(E_ALL);
P.S. Although your code will work without doing this, for security reasons it would be good to specify the JSON MIME type before outputting JSON from PHP, e.g.:
function saveNow() {
global $note_name;
// Write the file to disk
file_put_contents($note_name, $_GET['note']);
header('Content-type: application/json');
echo '{"saved":1}';
exit;
}

CI template - element is displayed in wrong place

I am having problems displaying views with a template.
My template looks like this:
<?php
$this->load->view('includes/header');
if($this->session->userdata('is_loggedin')!=1) //check if logged in
{
$this->load->view('includes/not_loggedin'); //includes this when not logged in
}
else //includes all this when is logged in
{
if(isset($content)) //check if content variable isnt empty
{
$this->load->view($content); //THIS IS MY CONTENT WHIC IS DISPLAYED IN WRONG POS
}
$this->load->view('includes/is_loggedin'); //
}
$this->load->view('includes/footer');
?>
By wrong position, I mean that my form is being displayed in the top lefthand corner outside of the HTML structure. Here is a copy from inspect element window. Notice where the div is located; the head tags are empty; and, the head information is in body.
<html lang="en">
<head></head> //head tags are empty
<body>
<div id="settings">...</div> //this is my loaded div
<meta charset="utf-8">
<title>Sludinājumu lapa</title> //head info outside tags
<link href="/assets/css/style.css" type="text/css" rel="stylesheet">
<div id="wrapper">....</div> //i need settings div inside wrapper div
</body>
</html>
Without loading that view, the HTML structure is fine. Also there is no problems with loading is_loggedin and not_logged into the views.
My header contains :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sludinājumu lapa</title>
<link rel="stylesheet" type="text/css" href="/assets/css/style.css">
</head>
<body>
<div id="wrapper">
And the footer contains:
<foter>
<p>developed by kriss</p>
</foter>
</div> //End of "wrapper" div
</body>
</html>
From the controller I am passing the data like this:
$data['content'] = $this->load->view('vchangeinfo');
$this->load->view('template', $data);
Any ideas why everything is so messed up?
Two ways of doing this:
Codeigniter views
Load it in advance (like you're doing) and pass to the other view
There is a third optional parameter lets you change the behavior of the function so that it returns data as a string rather than sending it to your browser. This can be useful if you want to process the data in some way. If you set the parameter to true (boolean) it will return data. The default behavior is false, which sends it to your browser. Remember to assign it to a variable if you want the data returned:
// the "TRUE" argument tells it to return the content, rather than display it immediately
$data['content'] = $this->load->view('vchangeinfo', NULL, TRUE);
$this->load->view ('template', $data);
// View
if(isset($content)) //check if content variable isnt empty
{
$this->load->view($content);
// OR don't know wich one works.
// echo $content;
}
Load a view "from within" a view:
<?php
// Controller
$this->load->view('template');
<?php
// Views : /application/views/template.php
$this->view('vchangeinfo');

Categories