April 21, 2013

HTML File Upload action – can this be hacked to spam endless file uploads

Adam’s Questions:

I have a question about hacking file uploads. Below shows the kind of setup I’m using and my concern is around the action that gives the full path to the upload script:

<form action="http://www.mydomain.com/scripts/php/photo_processing.php?page=join method="post" enctype="multipart/form-data">
  <input type="file" name="file" class="fileProfile"><br>

Can someone use the full path to send repetitive files constantly and then fill a web server disk space etc? eg: can you send files using this path outside the website and/or in a way that allows automated constant uploads?

Note: the php file has the following at the top – it is set to only this domain name – needed because of AWS Cloudfront POST limitation

header("Access-Control-Allow-Origin: http://www.mydomain.com");

No, they are basically prevented by cross domain policy. Unless the mydomain.com gives you access to it.

November 6, 2012

File replace in upload in php

Question by Mervyn

I would like to delete a file that is already exists and add the new one in the same folder.
I have taken the tmp name added it in a session. Deleted the existing already but it not movin in the new one.

$files = $_SESSION['Already'];

Answer by Starx

Try replacing the files. If the files name are exactly same, you don’t need to unlink them. Just using move_uploaded_file() will do.

Its important to know what is causing the error. Check your server error_logs for such informations.

April 18, 2012

jQuery validation – How to not accept a file extension

Question by Maxime Lepers

I would like to find a way to refuse a specific extension in a text field at form submission.

I have a field where you can specify a URL but this URL shouldn’t link to a PDF file.

I figured that there is a jQuery validation methods called accept that does exactly the contrary of what I want to do.

Is there a way to use with a not() function or something similar? It would be way easier than creating a custom validation method.

Answer by Starx

Here is any idea

var ext = $('#fieldid').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','jpg', ...]) == -1) {
    alert('invalid extension!');
April 4, 2012

How to get content of selected file by jQuery + Ajax

Question by user752433

I have a file upload element as hereafter:

<input type="file" id="uploadFile">

I can get the path & name of selected file by jQuery script as hereafter:

var filePath = $("#uploadFile").val();
var fileName = filePath.split('\').pop();

Could you please advise me how to get the file content (i thought it is in object or string format) and send it to server action.

Answer by Starx

First of all, you cannot get the path of an file-input element using $("#uploadFile").val();. It is a restriction by most of the modern browsers for security reasons.

Next, you have to upload the first, read the contents and throw the content back to the page using ajax.

You can use jQuery Form plugin to submit the form and grab the file contents on your backend.

March 30, 2012

read name and value from every define('NAME','VALUE'); inside a .php file

Question by elcodedocle

I’m implementing a php interface to process a .php file containing a bunch of define sentences defining constants with text values to translate by somebody.

The input is parsed sentence by sentence and shown in the interface to the translator who will input the translation in a html textarea and send it to the server

By the end of the process an output file would be generated, identical to the input .php file, only with the define values translated.

E.g. processing an input file ‘eng.php’ like this:

define ("SENTENCE_1", "A sentence to translate");

would give the translated output file ‘spa.php’ like this:

define ("SENTENCE_1", "The same sentence translated to spanish");

For this I would like to know:

1) What is the best way to parse the input file to get the constant names and values in an array? (Something like $var[0][‘name’] would be “SENTENCE_1” and $var[0][‘value’] would be “A sentence to translate”)

2) Would it be possible to get the translation from google translator shown in the input textarea as a suggestion to edit for the person who is translating it? How? (I read google translator api v1 is no longer available and v2 is only available as a paid service. Are there any free alternatives?)

Answer by Starx

Use get_defined_constants() to get the list of all the defined constants.

To get userdefined constant specially

$allconstants = get_defined_constants(true);
March 23, 2012

Copy file from remote server or URL

Question by Kris

I have the following code:

    $file = 'http://3.bp.blogspot.com/-AGI4aY2SFaE/Tg8yoG3ijTI/AAAAAAAAA5k/nJB-mDhc8Ds/s400/rizal001.jpg';
    $newfile = '/img/submitted/yoyo.jpg';

    if ( copy($file, $newfile) ) {
        echo "Copy success!";
        echo "Copy failed.";

and it always output “Copy failed”

copy(/img/submitted/yoyo.jpg) [function.copy]: failed to open stream: No such file or directory

my directory is set to 777.

any ideas? thanks!

Answer by Mark Biek

While copy() will accept a URL as the source argument, it may be having issues a url for the destination.

Have you tried specifying the full filesystem path to the output file? I’m assuming you’re not trying to put the new file onto a remote server.

For example:

$file = 'http://3.bp.blogspot.com/-AGI4aY2SFaE/Tg8yoG3ijTI/AAAAAAAAA5k/nJB-mDhc8Ds/s400/rizal001.jpg';
$newfile = $_SERVER['DOCUMENT_ROOT'] . '/img/submitted/yoyo.jpg';

if ( copy($file, $newfile) ) {
    echo "Copy success!";
    echo "Copy failed.";

The above worked nicely for me.

Answer by Starx

You cannot copy a file from a server without having access to it.

You can ftp_get() to open up a FTP connection and copy file.

$local_file = 'localname.zip'; // the nam
$server_file = 'servername.zip';
$conn = ftp_connect($ftp_server);

$login_result = ftp_login($conn, $ftp_user_name, $ftp_user_pass);

if (ftp_get($conn, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully copied";

If you want to download a file from URL

$fullPath = "filepath.pdf";

if ($fd = fopen ($fullPath, "r")) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    header("Content-type: application/octet-stream");
    header("Content-Disposition: filename="".$path_parts["basename"].""");
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
fclose ($fd);
March 21, 2012

How can I use getimagesize() with $_FILES['']?

Question by eric01

I am doing an image upload handler and I would like it to detect the dimensions of the image that’s been uploaded by the user.

So I start with:

if (isset($_FILES['image'])) etc....

and I have

list($width, $height) = getimagesize(...);

How am i supposed to use them together?

Thanks a lot

Answer by Starx

You can do this as such

$filename = $_FILES['image']['tmp_name'];
$size = getimagesize($filename);

// or

list($width, $height) = getimagesize($filename);
// USAGE:  echo $width; echo $height;

Using the condition combined, here is an example

if (isset($_FILES['image'])) {
    $filename = $_FILES['image']['tmp_name'];
    list($width, $height) = getimagesize($filename);
    echo $width; 
    echo $height;    
February 27, 2012

How to write a custom Zend validator to check the hash of a file against a database record

Question by blainarmstrong

I’m building a file repository where each file has a database entry associated with it. In that database, I include the sha1 hash value for the file. Also, for security reasons, I rename each file with a specific pattern, so I can’t check the filename directly via the form’s filename value.

I’m trying to prevent people from uploading the same file twice, so I want to create a form validator that takes the file being uploaded and checks the hash of the file against all the values in the database. If the hash is already in the database–and thus the file already exists–the validator should return false. How access the file from inside the validator class so I can calculate the hash?

Answer by Starx

Your question is very badly asked. So I will not dig into the logic of it.Sorry Here is a very simple example of how you can create a Custom Validation Class.

The most important thing you need to remember is two methods.

  1. isValid(): Returns either true or false through a logic
  2. getMessages(): Returns errors messages in case of invalid.

Here is a basic example of comparing whether a user is admin or not.

class CustomValidate_UserAdmin extends Zend_Validate_Abstract
    $admin = "username"; //I am using a static value this time

    protected $_messageTemplates = array(
        self::FLOAT => "'%value%' is not an admin"

    public function isValid($value)

        if($this -> admin == $value) {     
             return true;

Now use it

$element->addValidator(new CustomValidate_UserAdmin('username'));

This is a very simple example to understand. You can replace it with your logic with a lot of ease I think.


Add validation like this…

$element->addValidator(new CustomValidate_Hash('file/location', $hashvaluettocompare));

Now in your validation class

function isValid($location, $value) {
   if(hash_file("md5", $location)==$value) return true;
April 18, 2011

How to limit browse button to valid image files only

Question by sandeep

I want that whenever we click on browser button to upload so only image file is comes automatically instead of other file extension

Answer by Starx

You cannot restrict the upload, with just using HTML. There are two ways AFAIK

  • Read the file types and deny, after the form is submitted at the back end.
  • Use plugins like uploadify to restrict while selecting the file
July 23, 2010

PHP: open a file download dialog

Question by Hugh Valin

I have an MPEG file (.mpg) hosted in Amazon S3, that I want to link to a page I have, so the user will be able to download it from the page.
I have in my page a link:
bla bla

The link to the file works when I right-click it and choose “Save Target As” , but I would like it to work also when I left click it, and that it will open a file download dialog. right now, a left click will direct to a page that has the video directly played in it (in FireFox) or just won’t load (in Internet Explorer).

I am working in PHP, why does this happen?

Answer by Starx

Use this:

header('Content-disposition: attachment; filename='.$_GET['moviename.mpg']);

This will force the download box for whatever movie you have.


Please fill the form - I will response as fast as I can!