how to clear cache using PHP? - 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.

Related

Browser downloaded this unobfuscated PHP script. What is it doing?

As soon as I entered a site, my browser (chrome) downloaded this script. It's not obfuscated and not too long, and I think it's harmless, but I don't know PHP so i'm not sure. The file was called csync.php.
Chrome made it seem like this was the only file downloaded. Is it possible this is not true?
Could someone shed some light on what this is doing?
<?php
require_once("config/config.php");
require_function("util/StaticFunctions.php");
require_function("service/ServiceFactory.php");
require_function("bo/BoFactory.php");
require_function("data/DataFactory.php");
require_function("util/UtilFactory.php");
require_function("data/AkamaiLoggingService.php");
include 'config/setup/config-setup-skenzo.php';
include 'config/skenzo_request_variables.php';
header('P3P:CP="NON DSP COR NID CUR ADMa DEVo TAI PSA PSDo HIS OUR BUS COM NAV INT STA"');
header('Content-type: text/html');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: -1');
$visitorInfo = BoFactory::getVisitorInfo();
$vsid = $visitorInfo->getVisitorId();
$dataNames = VisitorInfo::$VSID_DATA_NAMES;
$mName = BoFactory::getInboundHttpRequest()->getSanitizedValueOfParam('type');
$mValue = BoFactory::getInboundHttpRequest()->getSanitizedValueOfParam('ovsid');
$vsCk = VISITOR_ID;
$vsDaCk = VISITOR_DATA;
$sepVal = VisitorInfo::$VALUE_SEP;
$sepTime = VisitorInfo::$TIME_SEP;
$vsDaTime = VisitorInfo::$VSID_DATA_TIME;
echo '<html> <head></head> <body> <script type="text/javascript" >';
$vsyncConf = array (
"vsCk" => $vsCk,
"vsDaCk" => $vsDaCk,
"sepVal" => $sepVal,
"sepTime" => $sepTime,
"vsDaTime" => $vsDaTime
);
echo "var vsyncConfig = " . json_encode($vsyncConf) . ";\n";
include(SKENZO_MEDIA_DIR. '/js/util/C2/modules/mnvdata.js');
echo '</script>';
echo "</body></html>";
if(AKAMAI_LOG_POSTBACK == $_SERVER['SERVER_NAME'])
{
define('AKAMAI_BULK_LOGGING', TRUE);
define('TEST_ENGINE_FROM_SERVING', '1');
try
{
$akLogService = new AkamaiLoggingService();
$akLogService->handleAkamaiBulkData();
echo '<!--var logged = 1;-->';
}
catch(Exception $e)
{
error("RTBLOG AKAMAI ERROR: " , $e , LOG_ALERT);
echo '<!--var logged = 0;-->';
}
}
else
{
if(AKAMAI_LOG_ORIGIN == $_SERVER['SERVER_NAME'])
{
echo '<!--var logged = 1;-->';
}
else
{
define('AKAMAI_BULK_LOGGING', TRUE);
define('TEST_ENGINE_FROM_SERVING', '1');
try
{
$akLogService = new AkamaiLoggingService();
$akLogService->handleGetRequests();
echo '<!--var logged = 1;-->';
}
catch(Exception $e)
{
error("RTBLOG AKAMAI ERROR: " , $e , LOG_ALERT);
echo '<!--var logged = 0;-->';
}
}
}
?>
The server you're visiting is poorly configured. As a result, instead of executing the PHP, the server sent it to your browser. Browsers don't execute PHP so you're safe.
If you care about the site you were visiting, the nice thing to do would be to contact support and refer it to this post.
A similarly named csync.php file has been reported in a couple of places online over the last couple of days. This, along with its reference to AKAMAI (a huge content delivery network), suggests that the mis-configured server isn't the 1st party site you were actually on, but a 3rd-party server that the site, along with many others, relies on.
File's apparent source: http://qsearch.media.net/csync.php
Similar reports (Google): https://encrypted.google.com/search?q=csync.php+download
I also saw this file drop into my downloads. The source is qsearch.media.net. If you visit media.net, you'll see it is part of the internet advertisement ecosystem. It's likely that there is a bug in one of their scripts. Sites using media.net's service then incidentally cause your computer to download this php file.
This is absolutely not server error of any websites, it is because my browser also download this script from multiple sites,one of them are from speedtest.net, i don't know what's hack is going on.

PHP - download dialog box for given videos url

I am pretty new in php .so hopefully this all make sense . I am using below script to extract url from database.I want down-loader will popup in browser while reading the url from database....
$q=" Select url from videos where id = '".$_REQUEST['id']."' ";
$result=mysql_query($q);
while( $rows =mysql_fetch_assoc($result) )
{
$url=$rows['url '];
//here i want code to send this url to down-loader of browser..
//and browser should popup the down-loader
$myarray1=array("url "=>$url );
}
I have searched codes on google but i don't understand how to use for this scenario...
First of all, you need to fix the SQL Injection problem.
Use MySQLi instead of MySQL
Here's a code:
$request_id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
if(!empty($request_id)){
$mysqli = new mysqli("localhost", "user", "password", "database_name");
$request_id = $mysqli->real_escape_string($request_id);
$query = "SELECT url FROM videos WHERE id='" . $request_id . "'";
$query_result = $mysqli->query($query);
if(!empty($query_result)){
if($query_result->num_rows > 0){
$my_result_array = array();
while($row = $query_result->fetch_assoc()){
$my_result_array[] = $row['url'];
}
}
}
mysqli_close($mysqli);
}
Concerning the download problem, you need to redirect the user to a PHP page with a specific header
<?php
$file_name = "";
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"" . $file_name . "\"");
header("Cache-Control: max-age=0");
?>
You need to add the $file_name and the specific Content-Type.
Here's a list of Content-Types: http://davidwalsh.name/php-header-mime
In order to redirect a user to the download page, you can use the PHP header() function.

PHP script header type image destroys session

I'm trying to write a small PHP script that uses a session to store a folder structure of images. Every time the side gets called it reads the next image out of session list and display it as content type of the side. When I call my script I sometimes get not the next image out of list but the next but one. When I write an output file to register every page request, I see that there were more than just one request. But if I look to my fire bug time line I don't see more than one request and there is no javascript running. If I show the image as part of an normal HTML page everything works gread. So what is going on here.
Would be nice if somebody can help me with this...
<?php
include("readDir.class.php");
define("IMAGE_SOURCE_PATH","img");
session_start();
//Inititalize new session context
try
{
if(!isset($_SESSION['id']))
initSessionConext();
}
catch (Exception $e)
{
exit();
}
$fotos = $_SESSION['fotos'];
//Handle wrapp around
try
{
if($_SESSION['id'] >= count($fotos))
initSessionConext();
}
catch (Exception $e)
{
exit();
}
$foto = $fotos[$_SESSION['id']];
if(strcasecmp($_SERVER['REQUEST_METHOD'],"get") == 0)
$_SESSION['id'] += 1;
//Error in session context return nothing
if(empty($foto))
exit(); //
switch(readDir::extension($foto))
{
case "png":
header('Content-Type: image/png');
break;
case "jpg": //Fall through to jpeg case
case "jpeg":
header('Content-Type: image/jpeg');
break;
}
$fp = fopen("test.txt","a");
fwrite($fp,$foto."\r\n");
fclose($fp);
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
readfile(IMAGE_SOURCE_PATH."/".$foto);
//echo $foto."<br>";
//echo '<img src="'.IMAGE_SOURCE_PATH."/".$foto.'" />';
//--------------- F U N C T I O N S -------------------------------
function initSessionConext()
{
$_SESSION['id'] = 0;
$_SESSION['fotos'] = getNewData(IMAGE_SOURCE_PATH);
}
function getNewData($path)
{
$extensions = array("jpg","png","jpeg"); //get data out of file system
$fotos = array();
$source = new readDir($path);
if(!$source->check())
throw new Exception('Could not find source for given path');
$fotos = $source -> readFilesWithextension($extensions);
if(!sort($fotos,SORT_STRING))
throw new Exception('Could not sort foto list in natural order');
return $fotos;
}
?>
So if I understand correctly, you're returning each image, one per time the image is loaded?
It seems likely to me that the browser is requesting the image twice: Once as a HEAD request, and the second time to get the content. This is commonly used to find out things like the Content-Length header before blindly downloading.
I would suggest making sure that strcasecmp($_SERVER['REQUEST_METHOD'],"get") == 0 before modifying the session.
Didn't solve the request problem at least. Use now time difference to differ between requests. Not nice but works out of the box...

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

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

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.

Categories