Protect a generate image with php - php

I'm having a problem here and I think people here can help me.
I have a file that generates an image, ler.php, and the file that loads the images through a while, carregar.php.
I need to block direct access to the images generated by ler.php, tried to make a system like this session:
carregar.php:
<?
$_session['a'] = 1;
while($a != 50) { echo "<img src='ler.php?imagem=$a'>"; $a++; }
$_session['a'] = 0;
?>
ler.php:
<? if($_session['a'] == 1) { //load image } ?>
The result is the only loading the first image.
I'm trying to now use the $_SERVER ["PHP_SELF"], placing the IF of ler.php, what happens is I load it through <img src=''> she identifies as carregar.php.
Who has the best solution?
I've tried several ways with $_SESSION and it seems to not really work.

I could suggest two ways:
Easy to implement, less protective: in ler.php check that $_SERVER["HTTP_REFERER"] refers to "carregar.php".
A little bit more complicated: in carregar.php generate an unique code for each image you're going to output and store it in $_SESSION. Then pass the code to ler.php as a GET parameter. In ler.php check if the code exists in $_SESSION object, then generate an image and remove the code from $_SESSION.

I have a hard time identifying the problem, but your use of the session is going to lead to unexpected results:
You are adding 50 (I guess...) image tags to a page and right after you have added these tags, you set the session variable to 0.
The browser only loads a few files from the same server at the same time, so when the script is done and the first image is loaded, the browser is going to request the next image but that will fail as you have set the session variable to 0 already.
The only way to reliably set the session variable to 0 after all images have loaded, is an ajax request from your page that checks and triggers after all images have completely loaded.

Good! I managed to resolve one way and improvised without using AJAX:
ler.php:
<?php
if(isset($_SERVER["HTTP_REFERER"])) {
$check2 = (strpos($_SERVER["HTTP_REFERER"], 'carregar.php') > 0) ? true : false;
if(print_r($check2) != 11) {
// Blank
}
} else {
if(isset($_SERVER["HTTP_REFERER"]))
{
// Load Image
}
if(!isset($_SERVER["HTTP_REFERER"]))
{
// Blank
}
?>
So, the image only can be loaded into my page. Maybe...

Related

Is there a way to execute required php file once per session?

I am new to php and have just written a basic index.php that will display family tree information for an individual based on input id.
The index.php includes a file called "xml-people-list.php" which loads the information from the family tree and creates a sorted list of people.
My problem is that every time you click on a person to display their details, the included php is reloaded which causes the read from file and creation of sorted list to happen again.
Is there a way to only run this code once per session to avoid multiple loads?
I tried to look at session variables but wasn't sure if they would help or how to use them in this case or if there is another way?
Contents of "xml-people-list.php:
<?php require 'xml-load-person.php';
if (file_exists('people.xml'))
{
$people = simplexml_load_file('people.xml');
foreach ($people->person as $person)
{
$person_list[(string)$person['ID']] = strtoupper($person->FamilyName) . ", " . $person->GivenNames;
}
asort($person_list);
}
else
{
exit('Failed to open people.xml.');
}
?>
Thanks for any help!
Yes, you could use session variables. If you wanted to only parse the list once per visitor, and then "cache" the result into a session variable, you could do something like this (for a simple example):
if (!empty($_SESSION['person_list'])) {
// Here we fetch and decode the the ready list from a session variable, if it's defined:
$person_list = json_decode($_SESSION['person_list']);
}
// Otherwise we load it:
else {
require 'xml-load-person.php';
if (file_exists('people.xml'))
{
$people = simplexml_load_file('people.xml');
foreach ($people->person as $person)
{
$person_list[(string)$person['ID']] = strtoupper($person->FamilyName) . ", " . $person->GivenNames;
}
asort($person_list);
// Here we assign the ready list to a session variable (as a JSON string):
$person_list = json_encode($person_list);
$_SESSION['person_list'] = $person_list;
// Here we revert the JSON-encoded (originally SimpleXML) object into a stdClass object.
$person_list = json_decode($person_list);
}
else
{
exit('Failed to open people.xml.');
}
}
You will need to call session_start() in your file (either this one, or any other file including it, but importantly before any output is sent to the browser). Homework: Read up on sessions in PHP.
Update: Since SimpleXML objects can't be serialized, and since adding an object to $_SESSION causes serialization, I've updated the answer to json_encode/decode the object. Yes there's a bit of processing, but that'd be the case with the default serialization as well, and json_en/decode is fairly light-weight. Certainly heaps lighter than parsing XML on each page load!
Be aware that the returned object will be a stdClass object, not a SimpleXML object. I'm assuming it won't be a problem in your use case.
Maybe try require_once() function
1) First of all, try to see if your buttons are anchor tags then be sure that the href attribute is directing to # example: <a href="#">
2) try to use include_once instead of requiring
3) if you tried this and these couple solutions didn't work for you you can send the id of a person using the global $_GET variable
//this should be you URL http://localhost/projectname/index.php?person_id=1
// your href of each person should appoint to their URL
// <a href="index.php?person_id=1">
you can use this $_GET['person_id'] and store it into a variable so it will give you the id of person.

PHP: Dynamic Pages with multiple dynamic content

I'm using this a particular code to dynamically load content on a webpage.
Problem is, I want to use it to load multiple things on the same page. How do I go about making this possible? I've already isolated the problem to the fact that the second instance of the code that runs replaces the entire URL instead of appending an additional ?="pageurl" but I'm stuck right there.
I've got a second script that uses the variable p instead of b so the browser knows to load p's content in a different location.
This is what the code does:
http://www.youtube.com/watch?v=Qg-EBdNaUbo
[edit]
Not sure why you guys can't see the link, it explains everything. I'm calling the script via a link Here is the link again youtube.com/watch?v=Qg-EBdNaUbo
CODE:
<?php
$pages_dir = 'pages';
if(!empty($_GET['b']))
{
$pages = scandir($pages_dir, 0);
unset($pages [0], $pages [1]);
$b = $_GET['b'];
if(in_array($b, $pages))
{
include($pages_dir.'/'.$b);
}
else
{
echo 'sorry page not found';
}
}
else
{
}
?>

How to rotate two strings or functions on page refresh?

I have two values, i want to echo one of them on page refresh and rotate it.
If the two values are Hello and Hi.
Hello > Page refresh > Hi > Page refresh >Hello > Page Refresh > Hi
I tried shuffle, rand, mt_rand but sometimes it just keep the same value instead of rotating to the next.
Thanks.
<?php
session_start();
if (!isset($_SESSION["count"])) $_SESSION["count"] = 0;
$_SESSION["hits"]++;
echo ($_SESSION["hits"]%2 == 1?"Hi":"Hello");
// or with functions
if ($_SESSION["hits"]%2 ==1){
my_func_1();
} else {
my_func_2();
}
its basically a page hit counter with logic on what to print depending on if the page hits are even or odd.
To rotate the string, something random is definitively not what you are seeking.
First to have to decide the scope of the rotation.
Based on the distributed page from the server ? (odd pages hays hi) or based on the user that si visiting you (so the rotation is always visible to you, ever if other users have also the rotation)
I guess you want based on user:
So you have to link the rotation to the user that visit you,
that can be managed through a cookie or through a PHP session
set the cookie and based on the value, say hello or hi
// before sending headers
$say = isset($_COOKIE['say'])?$_COOKIE['say']:1;
setCookie('say', $say==1?2:1);
if ($say == 1)
echo "hello";
else
echo "hi";
You can do the same thing with a PHP session
That gives you an idea

What is the proper way of only having one page with get requests php?

For instance, I have viewpost.php and it's set up as needed and I only need to change the content within divs in there.
For example, I'm going to have to do viewpost.php?id=1,2,3 etc. But should I do EVERYTHING off index.php using index.php?action=viewpost&id=1?
Then also, do I use if statements, or do I communicate with my database using those get requests?
Overall, I plan to use modrewrite anyway, but I am clueless on the proper way to set up loading multiple pages off one, or a few php files.
I have a template and I just need to fill it using database data.
Easiest way is something very basic like this (Not very secure though)
$page = $_GET["action"];
if($page == null)
{
$page = "main";
}
if (file_exists("content/$page.php"))
{
include ("content/$page.php");
}
else
{
include ("includes/404.php");
}
A better solution is to use something like http://www.smarty.net/ to handle templating and content loading. Slightly more complicated, but most likely worth the extra effort if you're doing anything beyond a very simple website.
index.php?action=viewpost&id=1 this code in index:
if(isset($_GET['action']) && isset($_GET['id']))
{
$id = $_GET['id'];
if($action == "viewpost")
{
// action is viewpost
if(!ctype_digit($id))
{
// id isnt digit
die();
}
else
{
// viewpost
include('viewpost.php');
}
}
viewpost.php could look like:
just to be sure nothing bad happens when going right to viewpost.php you could see in the url if viewpost.php exists, or just do the security here (!ctype_digit($_GET['id']))
// since its already been secured with !ctype_digit, we can run queries right away
$q_findPost = mysqli_query($mysqli, "SELECT * FROM posts WHERE id=$id");
$r = mysqli_fetch_assoc($q_findPost);
// div stuff

Remembering text resizing across different pages on a web site using PHP SESSIONS

So after reviewing some tutorials on how to change text size and creating my own using PHP I was wondering how can I have my text size remembered across many different pages on my web site using PHP SESSIONS?
Here is the PHP text sizer code below.
$size = 100;
if(isset($_GET['i']) && is_numeric($_GET['i'])) {
$s = $_GET['i'];
}
if($s == TRUE){
$size = ($s * 1.2);
}
if(isset($_GET['m']) && is_numeric($_GET['m'])) {
$m = $_GET['m'];
}
if($m == TRUE){
$size = ($m * 0.8);
}
if(isset($_GET['n']) && is_numeric($_GET['n'])) {
$n = $_GET['n'];
}
if($n == TRUE){
$size = 100;
}
Here is the CSS code.
#content {
font-size : <?php echo $size; ?>%;
}
And here is the xHTML.
Increase<br />
Decrease<br />
Normal<br />
First all, make sure you out put session_start() on all pages, before any content is posted.
From here, you're able to set session variables (which will be saved into a session cookie typically).
So when your user clicks a link, PHP should set something like $_SESSION['i'] = $_GET['i']; and then when you visitor comes back to a page, you just see if $_SESSION['i'] has a value - if it does, use this value, if not, revert to default.
Check out this great tutorial: php sessions - why use them?
Just don't use $_GET variables, use $_SESSION vars instead. Be sure to include the relevant session_start() functions and all that.
As mentioned, you'll want to your the $_SESSION object instead of $_GET. You'll need to add a call to session_start() at the start of each page (check the examples on this link; will show you how to use sessions on a basic level). You may also want to take a look at Local Web Storage (browser-based) in HTML5. Check out this tutorial. It's quite easy to implement. Of course, not all browsers implement web storage, but it's pretty ubiquitous (Depending if you want to support < IE8)

Categories