Showing posts with label PHP HEADERS. Show all posts
Showing posts with label PHP HEADERS. Show all posts

Tuesday, 18 September 2018

PHP Caching Headers

Yesterday I looked at how to control browser caching with Apache's mod_expires and today look at how to set the caching/expiry time with headers in PHP to either make sure the resulting data is never cached by the browser, or is cached for a set amount of time.

Make sure a page is never cached with PHP

To make sure the page is never cached (or whatever other dynamic content generated from PHP such as images, RSS files etc) add the following to the start of your script:
$ts = gmdate("D, d M Y H:i:s") . " GMT";
header("Expires: $ts");
header("Last-Modified: $ts");
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");

To set the amount of time to cache

If instead you want the output from the script to be cached for a certain amount of time, set the expires header to a time in the future. For example, to make it so the browser will cache the output for 1 hour do this:
$seconds_to_cache = 3600;
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache");
The Cache-Control header requires the number of seconds to cache the file so in this example it's 3600 because 60 seconds x 60 minutes = 3600.

Related posts:

410 "Gone" with PHP

If a resource has been removed from a website, will not be available again and no forwarding address is available then it should return a 410 "Gone" HTTP status. This post explores the 410 status compared with a 404 "Not Found" and 301 "Moved Permanently" and shows how to do a 410 with PHP.

410 Gone

In most cases, developers and webmasters let their webservers respond with a 404 Not Found response code after they have removed a file or webpage. There is nothing necessarily wrong with this but there are two alternatives; the first is to do a permanent redirect using a 301 status code to some other equivilent resource, and the second is to send a 410 Gone status code which indicates the resource has been taken away and this change is permanent.
In theory, sending a 410 status from a deleted web page should stop search engine spiders and other bots from continually requesting pages that no longer exist (for example I've seen Yahoo!'s Slurp bot continue to ask for 404 pages for several years after they were removed) but in practise they may well also ignore a 410. But at least it's worth a try :)

410 Headers with PHP

Sending a 410 header with PHP is as simple as this:
header("HTTP/1.0 410 Gone");
It's advisable to then also send some text or a regular HTML web page after the header so that the browser as something to display because many of them will simply show a blank page.
Something as simple as this is better than nothing:
<?php
header("HTTP/1.0 410 Gone");
?>
The requested page has been removed.
but you can include full HTML and therefore include your website's template as part of the page returned.

Related posts:

Image headers with PHP

If you ever need to send an image file with PHP from the web server to the web browser you need to add an additional header using the header() function so the browser knows it's an image and not regular HTML. This post looks at the headers you need to use.
There are a variety of methods for creating and manipulating images with PHP, as well as simply opening the file and then sending the contents to the web browser. All of these methods require setting the Content-Type header to the image's mime type so the browser knows what sort of file type it is.
The following examples show doing this for GIF, JPEG and PNG images, and then use the readfile() function to pass through the content of the file to the web browser.

GIF:

header('Content-Type: image/gif');
readfile('path/to/myimage.gif');

JPEG:

header('Content-Type: image/jpeg');
readfile('path/to/myimage.jpg');

PNG:

header('Content-Type: image/png');
readfile('path/to/myimage.png');
You can use the same header functions for sending other mime types as well, for example when sending a PDF or Flash file to the browser.

Related posts:

Thursday, 6 September 2018

Sending a CSV file to the web browser with PHP


In the past I've written about how to save data as a CSV file using PHPMySQL queries and mysqldump and in this post show how to send the results of this data to a web browser setting the headers correctly with PHP so the browser gives you a "save as" dialog instead of displaying it on the page. The headers also include the filename which is supplied as the default in the save as dialog.
The headers look like so, substituting filename.csv for the name you would like:
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="filename.csv"');
Then it's simply a matter of echo'ing out the CSV data to the web browser.

Compressing the data with ob_gzhandler

In order to cut down the amount of data actually transferred, it's a good idea to use PHP's ob_start() in combination with the gzhandler callback which will compress the output before sending it to the browser. The browser decompresses it and you still end up with a plain text file:
ob_start('ob_gzhandler');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="filename.csv"');

Reading from a file

The CSV data will most likely come from a variable, from looping through data from a database or from a file. To echo the contents of the file to the browser do this:
readfile($filename);
where $filename is the filename of the file.

Tuesday, 4 September 2018

The header of the PHP login page does not work

I was trying to make a login form which redirects to my index page. But I think the header() function used in the second php script of the admin_login.php is not exactly working and thus if the username and password are correct also then the browser is not redirection to the index.php page. I find that the first hearder() is working properly because when ever after login I reload the browser the page is redirected to the index.php Please help me out how to rearrange the codes to get the desired results. Thanks in advance.

admin_login.php

<?php 

    session_start();
    if(isset($_SESSION["manager"])){
        header("location: index.php");
        exit();
    }
?>

<?php 

    if(isset($_POST["username"]) && isset($_POST["password"])){

        $manager = preg_replace('#[^A-Za-z0-9]#i','',$_POST["username"]);
        $password = preg_replace('#[^A-Za-z0-9]#i','',$_POST["password"]);

        include("../storescript/connect_to_mysql.php");

        $sql = mysql_query("SELECT id FROM admin WHERE username = '$manager' AND password = '$password' LIMIT 1 ");

        $existCount = mysql_num_rows($sql);

        if($existCount == 1)
        {
            while($row = mysql_fetch_array($sql)){
                $id = $row["id"];
            }
            $_SESSION["id"] = $id;
            $_SESSION["manager"] = $manager;
            $_SESSION["password"] = $password;

            header("location : index.php");
            exit();
        }
        else
        {
            echo ("The given information is incorrect. Please <a href='index.php'>click here</a> to try again. ");
            exit();
        }
    }

?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>GROCERY WORLD STORE ADMIN</title>
<link href="../../css/structure/template.css" rel="stylesheet" type="text/css">
<link href="adminpage.css" type="text/css">
<link href="adminpage.css" rel="stylesheet" type="text/css">
</head>

<body>

    <!--CONTAINER-->
    <div class="Container">

        <?php
            include_once("../../template_header.html");
        ?>

        <!--CONTENT AREA-->
        <div class="Content">

            <div style="margin: 10px;" align="left">

                <form action="admin_login.php" method="post" name="adminLogin">
                    <table width="300" border="0">
  <tr>
    <td>username</td>
    <td><input type="text" name="username"></td>
  </tr>
  <tr>
    <td>password</td>
    <td><input type="password" name="password"></td>
  </tr>
  <tr>
    <td><input type="submit" value="Login"></td>
    <td><input type="reset" value="Clear"></td>
  </tr>
</table>

                </form>

            </div>

        </div>

        <!--FOOTER AREA-->
        <?php
            include_once("../../template_footer.html");
        ?>

    </div>

</body>
</html>

connect_to_mysql.php

<?php
    $mysql_host = "myhostname";
    $mysql_db = "mystore";
    $mysql_user = "mybuilder";
    $mysql_pwd = "123";
    $conn = mysql_connect("$mysql_host","$mysql_user","$mysql_pwd") or die(mysql_error());//SETING UP CONNECTION WITH SQL DATABASE
    mysql_select_db("$mysql_db", $conn) or die("No Database");//SELECTING DATABASE
?>

index.php

<?php 

    session_start();
    if(!isset($_SESSION["manager"])){
        header("location: admin_login.php");
        exit();
    }

    $managerID = preg_replace('#[^0-9]#i','',$_SESSION["id"]);
    $manager = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["manager"]);
    $password = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);

    include("../storescript/connect_to_mysql.php");

    $sql = mysql_query("SELECT * FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1");

    $existCount = mysql_num_rows($sql);

    if($existCount == 0)
    {
        echo "Your record is not present in our database.";
        exit();
    }

?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>GROCERY WORLD STORE ADMIN</title>
<link href="../../css/structure/template.css" rel="stylesheet" type="text/css">
<link href="adminpage.css" type="text/css">
<link href="adminpage.css" rel="stylesheet" type="text/css">
</head>

<body>

    <!--CONTAINER-->
    <div class="Container">

        <?php
            include_once("../../template_header.html");
        ?>

        <!--CONTENT AREA-->
        <div class="Content">

            <div style="margin: 10px;" align="left">

            <h3 id="Style1">Hello ADMIN MANAGER. What would you like to do today?</h2>
            <p>
            <a href="#">Update products</a><br>
            <a href="#">Logout</a>
            </p>
            </div>

        </div>

        <!--FOOTER AREA-->
        <?php
            include_once("../../template_footer.html");
        ?>

    </div>

</body>
</html>


if(isset($_SESSION["manager"])){
  include("index.php");
  exit();
}

$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
include("index.php");
exit();

This is probably outputting some spaces or new line. The include will work where the header will not.
?>

<?php

Monday, 3 September 2018

PHP The header ('Content-Type: text / plain'); needed at all?

I didn't see any difference with or without this head information yet.


Define "necessary".
It is necessary if you want the browser to know what the type of the file is. PHP automatically sets the Content-Type header to text/html if you don't override it so your browser is treating it as an HTML file that doesn't contain any HTML. If your output contained any HTML you'd see very different outcomes. If you were to send:
<b><i>test</i></b>

Content-Type: text/html would output:
test
whereas Content-Type: text/plain would output:
<b><i>test</i></b>

TLDR Version: If you really are only outputing text then it doesn't really matter, but it ISwrong.

Contents of PHP header content: The attachment forces the .php file or online

I want to download a single .mp3 file from my site but when using this code it forces a .php in Firefox and Safari. But in chrome it will send force the file as inline and play on the page. How can i get them to actually download a .mp3 file?

$track = $_SERVER['QUERY_STRING'];

if (file_exists("/home/user/gets/" .$track)) {
    header("Content-Type: audio/mpeg");
    header('Content-Length: ' . filesize($track));
    header('Content-Disposition: attachment; filename="test.mp3"');
    $str = "/home/user/gets/".$track;
    readfile($str);
    exit;
} else {
    header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
    echo "no file";
}

I have also tried to download a .zip file as well and changing the Content-Type to application/ocetet-stream but it forces .php files on all browsers.
//$track = $_SERVER['QUERY_STRING'];
$track = 'testfile.zip';
if (file_exists("/home/user/gets/" .$track)) {
    header("Content-Type: application/octet-stream");
    header('Content-Length: ' . filesize($track));
    header('Content-Disposition: attachment; filename="test.mp3"');
    $str = "/home/user/gets/".$track;
    readfile($str);
    exit;
} else {
    header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found', true, 404);
    echo "no file";
}


I think filesize($track) is wrong, it should be the whole path filesize("/home/user/gets/".$track). This would cause php to output error messages, preventing you from setting the content-length and disposition header.

When to use the header ('Content-Type: application / json') in PHP

I've been trying to figure out what's really the usage of header('Content-Type: application/json') in php scripts and I've found different questions and answers on stackoverflow about this subject but I still don't completely get it...

So here's the question : I've seen in some php projects this line of code, and I'm trying to understand
  • if this is used when another web page is calling this actual script (with ajax for example) so that the calling page can get a json from the php page
OR
  • if this script means that the php page is going to deal with json sent from another web page. Or maybe something else ???
Another thing that could help me if answered, lately I've been retrieving json from a resource (external url) with cURL and I had to put this header (Content-type:application/json) in the request. Did I send this header to the exertnal resource or was this MY header so that I can deal with the returned json ?
thanks

You should always set the Content-Type for any HTTP response to describe what you're serving in that response.
Whether it's JSON or something else, and whether it's for an AJAX request or any other kind of request.

You should also set the Content-Type for any request to describe your POST payload.

That are the benefits of using .css on .php with content-type: text / css?

What are the benefits of using a CSS external stylesheet over a php file set to content-type: text/css? If you place this header at the top of a PHP file I feel like you have so much more potential:

<?php
    header("Content-type: text/css");

    if($query_string = "contact_us") {
        #nav {}
    }
?>

If there are no downfalls (and I checked how they were cached in Chrome's Network Panel and I believe it's the same), isn't it kind of like whether to use .html or .php?
Thanks for any feedback.

Here are some differences:
  • PHP will create extra CPU / memory overhead compared with serving purely static CSS. Probably not all that much, but still a consideration. The more processing you do the bigger a deal it is, obviously.
  • You can't push PHP files to a CDN
  • SASS and LESS have been developed to deal with any dynamic features you might need so PHP isn't likely necessary
  • Sounds like you're worried about serving more CSS than is needed for certain pages. Realistically it's not an issue since browsers will cache the CSS after the first download.
Additional thoughts:
I wrote a UI template engine that isolates both JS and CSS code to only the specific views on which they are used. If a CSS or JS is used more than once, it is pushed to the "kitchen sink level" and included globally. This limits selector conflicts and also best balances the number of HTTP requests and total download size per request. Also keeping relevant code (i.e. button event listeners or page / element-specific styles) close together helps with more rapid programming, especially for non-expert teams / developers.

PHP header ("Content-Type: image / png ")

when implement this code i have no image

  <?php

  include('confing.php');
  echo '<img src="getImage.php?id=2" >';

  ?>

file => getImage
<html >
<body>
<?php

include('confing.php'); 

$id = $_GET['id'];
$sql="SELECT * FROM images WHERE id=$id ";

$result=mysqli_query($connection,$sql);

$row = mysqli_fetch_assoc($result);

    // Set the content type header - in this case image/png
    header("Content-Type: image/png");
    echo $row['content'] ;

?>

body> html> body html body> html> body html body> html> body html

The errors you are getting:
  • Undefined index ID: It would appear that you are calling it without passing the ID argument. Obviously you should check that. But also, you should add some error checking to your code to ensure that it doesn't crash if the ID is not passed, or if the ID is invalid.
  • Undefined variable $connection: Your database connection variable is not set. Maybe you config.inc include doesn't actually set the connection? Or maybe you've got the variable name wrong? You need to check your config.inc to find out why this is happening. In any case, this leads directly onto the next error...
  • mysqli_query expects connection parameter: Because the $connection variable is not set, your DB query can't be run. Some error checking here would be helpful, even if you do sort out the connection variable, as there may be other reasons the connection may fail.
  • mysqli_fetch_assoc expects result parameter: This occurs because the result variable is not set due to the query not being run. You should add some error checking for this as well, since there may be other reasons why a query fails to run.
The errors didn't even get as far as hitting the header() function call, which would also fail because the program has already output some content. You should remove the <html><body> tags from the top of the program, as they are not necessary for outputting an image; in fact, they would cause the image to be invalid.

PHP how to use the content type: image / jpeg correctly? advertisements

I've created a page "student_picture.php" using the content-type:image/jpeg. im having problem when I want to add other text in that same page..

here is the sample of my code:
<?php
session_start();

if(!isset($_SESSION["StudentNo"])){
    header("location:login.php");
}

$StudentNo = $_SESSION['StudentNo'];

require("includes/connection.php");

$sql = "SELECT StudentPicture from dbo.Students where StudentNo = '$StudentNo'";
$stmt = sqlsrv_query( $conn, $sql );

if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
    $img = $row['StudentPicture'];

    if ($img == null ) {
        echo "<img src='img/default_pic.gif'>";
    } else {
        $img =  trim($img);
        header('Content-Type: image/jpeg');
        echo $img;
    }

    echo $StudentNo;
}
?>

The image is successfully displaying but the echo $StudentNo is not displaying.. can anyone help me with my prob? thanks in advance.

You might need to use following code :
<?php 

$image = 'http://www.example.com/image.jpg';

$info = getimagesize($image);

header('Content-Type: '.$info['mime']);

echo file_get_contents($image);

exit;

?>

PHP header (& ldquo; Content-Type: image / jpeg & rdquo;); returns a broken image advertisements

Im fetching an blob image from my database, but it returns broken.

If i remove header("Content-Type: image/jpeg");
it returns the file extension at it should be since its a PNG file
‰PNG  IHDR\r¨fÆÉIDAT

Any ideas whats the problem ? And yes. i tried the header("Content-Type: image/png");also
I have tried with ob_start and ob_end_flush();
code
  ob_start();

    $query = $db->query("SELECT `image` FROM `userdetails` WHERE id = '{$_SESSION['uid']}' ");
    $row = $query->fetch(PDO::FETCH_ASSOC);

    echo $row['image'];

    header("Content-Type: image/jpeg");
    ob_end_flush();

thanks

What you ask about in your question is subject to many parameters of which I fear your question does - if at all - scratch only some of them.
What pops into the eye is the PNG header:
‰PNG  IHDR\r¨fÆÉIDAT

does not look broken. So you probably did have a problem to store the image into the database. Maybe the data was truncated / modified and this change got unnoticed?
One way to deal with that is to create a checksum of the files before putting them into the blob to be able later on to verify the data-integrity.

PHP header ('Content-Type: image / jpeg') works on localhost but does not work on a real server

I want to hide the image url from users, so I am using php header() function, the problem raises when I host my website on Bluehost, it works fine on localhost. here is my function to access the image.

function download($name = '', $tiny = '0') {
    if ($name != '') {
        $file = $this->mdl->get_file($name);
        if($file){
                $mime = mime_content_type('./'.$file->path.$file->name);
                header('Content-Type: '.$mime);
                echo file_get_contents('./'.$file->path.$file->name);
        }
    }
}

here is get_file function on model:
function get_file($name=''){
    if($name!=''){
        return $this->db->select('*')
        ->from('docs')
        ->where('name',$name)
        ->get()
        ->row();
    }
    return false;
}

any helpfull answer is appretiated.

Basically this type of problem occur when any space or new line exist out of the php tags or anything printed before the header function.
  • Try this :
ob_clean(); before the header

Force file download code works on localhost but does not work on real server in PHP

I'm php programmer of beginner. I have write code to download file of any type.

When I click on download link it goes to download.php file. I work on local server but not working on server.
My code is:
header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');    //application/force-download
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        //header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit();

Is my code wrong or does server need some settings?

by using code written by me. this problem is solved. if anybody have same issue. please try this code. it works for me very good.
$file_name ='../img/files'.DS.$_GET['file'];
if(is_file($file_name)) {
        if(ini_get('zlib.output_compression')) {
                ini_set('zlib.output_compression', 'ON');
        }
        switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
                case 'pdf':  $mime = 'application/pdf'; break; // pdf files
                case 'zip':  $mime = 'application/zip'; break; // zip files
                case 'jpeg': $mime = 'image/jpeg'; break;// images jpeg
                case 'jpg':  $mime = 'image/jpg'; break;
                case 'mp3':  $mime = 'audio/mpeg'; break; // audio mp3 formats
                case 'doc':  $mime = 'application/msword'; break; // ms word
                case 'avi':  $mime = 'video/x-msvideo'; break;  // video avi format
                case 'txt':  $mime = 'text/plain'; break; // text files
                case 'xls':  $mime = 'application/vnd.ms-excel'; break; // ms excel
                default: $mime = 'application/force-download';
        }
    header('Content-Type:application/force-download');
        header('Pragma: public');       // required
        header('Expires: 0');           // no cache
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
        header('Cache-Control: private',false);
        header('Content-Type: '.$mime);
        header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
        header('Content-Transfer-Encoding: binary');
        //header('Content-Length: '.filesize($file_name));      // provide file size
        header('Connection: close');
        readfile($file_name);
        exit();
}

Tuesday, 28 August 2018

Header redirects to the page that does not exist?

I have this strange behavior, PHP headers act differently on webserver and localhost.

Example
On web hosting function
header("Location: /content/".$page['url_language']."/".$page['direction']."/".$w['id']."/")

redirects to index.php and the /content/".$page['url_language']."/".$page['direction']."/".$w['id']."/" are send as parameters.
But then i do the same on localhost and my browser redirects to page /content/".$page['url_language']."/".$page['direction']."/".$w['id']."/"
That does not exist, not the index. How this happens, there is no .htaccess on web server and localhost to change the settings. Maybe I missing some settings, any suggestions?

The HTTP/1.1 ask for an absolute URI with the parameter "location:". Some explorer accept relative paths, but your problem may come from here.
If it's an absolute path on the server, his configuration may be different from your local file. Check if /content is really in the root of the server (and not in a /www or thing like that).
Here a little code you could use to test your global variables.
<?php
/* Redirection to an other webpage in the same file */
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>`

Wednesday, 3 June 2015

HTTP Redirection in PHP

Allows to perform PHP redirection (must be placed before any browser output).
  <?php
       // stick your url here
        header('Location: http://you_address/url.php');
        exit;
    ?>