cereal 1,524 Nearly a Senior Poster Featured Poster

@accra

A part Hiroshe's suggestion which I would strongly consider, to explain the pratical issue with your script, the problem is this:

$salt = uniqid(mt_rand()+microtime(true), true);
$password=hash('sha256',$password.$salt); // Encrypted password

Both in your registration and forget pages you are appending a $salt variable to the password. If you do this, then you have to save the salt value to the database, separated from the password, for example:

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `email` varchar(255) NOT NULL,
  `password` char(64) NOT NULL,
  `salt` varchar(50) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 

At the moment in your login page you are not considering anymore the salt, which will change and if you don't save the original value created during the registration or recovery (forget page) process, then you cannot sign into the secure session.

So, when you verify the login, the query at line 16 of the login page becomes:

$query = "select * from users where email = '$email' and password = (sha2(concat('$password', salt), 256))";

Here we're using the sha2() function in MySQL which allows to use SHA-224, SHA-256, SHA-384, and SHA-512 hash functions. The first argument of sha2: is a concat() between the password in clear text and the salt column that matches with the searched email; the second argument is the hash value, which in this case is 256. So with a single query you can check if the user is allowed.

Note 1: uniquid() is …

cereal 1,524 Nearly a Senior Poster Featured Poster

On line 13 you're creating the hash without the salt:

$hashed = hash('sha256',$password);

So, it cannot generate the same hash, if you're going to use random salts for each user, then you must save it to the database.

Right now it probably works during registration & login because you create a cookie, and there's a check here:

if( isset($_SESSION['email']) || isset($_COOKIE['email'])) { // if session or cookie is stored
  header("Location: zalla/fbdashboard.php"); // redirect to home, no need to logged in
  exit();
}

that will redirect without matching the password.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, can you paste an output hash? For example, I tried this:

And it returns the same hash of md5() in PHP:

echo md5("hello"); // 5d41402abc4b2a76b9719d911017c592

But I don't know JAVA well, so my example could be wrong.

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, then try:

<?php

    # initialize the variable
    $code = '';

    # check if it exists and if it is alpha-numeric
    if(array_key_exists('code', $_GET) && ctype_alnum($_GET['code']) === true)
    {
        $code = $_GET['code'];
    }
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <div class="form-group">
        <input type="password" id="password" name="password" size="25"  class="form-control input-lg" placeholder="Enter Password">
    </div>

    <div class="form-group">
        <input type="password" id="passwordconfirm" name="passwordconfirm" size="25"  class="form-control input-lg" placeholder="Re-Enter Password">
    </div>

    <div class="form-group">
        <input type="submit" value="Reset Password" name="login" class="btn btn-default btn-lg btn-block" />
    </div>
    <?php
        # adding hidden input $_POST['code']
        echo "<input type=\"hidden\" name=\"code\" value=\"{$code}\" />";
    ?>
</form>

Then in your script check for $_POST['code']. Otherwise append it to the action url of the form and then, while receiving the input, search for $_GET['code']:

<?php

    # initialize the variable
    $action = htmlspecialchars($_SERVER['PHP_SELF']);

    # check if $_GET['code'] exists
    if(array_key_exists('code', $_GET) && ctype_alnum($_GET['code']) === true)
    {
        $action .= '?code='. $_GET['code'];
    }

?>
<form method="post" action="<?php echo $action; ?>">
    <div class="form-group">
        <input type="password" id="password" name="password" size="25"  class="form-control input-lg" placeholder="Enter Password">
    </div>

    <div class="form-group">
        <input type="password" id="passwordconfirm" name="passwordconfirm" size="25"  class="form-control input-lg" placeholder="Re-Enter Password">
    </div>

    <div class="form-group">
        <input type="submit" value="Reset Password" name="login" class="btn btn-default btn-lg btn-block" />
    </div>
</form>

Note that by using this last method, the first part of your script, i.e.:

if(!empty($_GET['code']) && isset($_GET['code']))
{
    # code

Will always run. To avoid it, add $_SERVER['REQUEST_METHOD'] == 'GET' to the statement:

if($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['code']) && ! empty($_GET['code']))
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, try to append the query string to the action of the form:

<form method="post" action="receiving.php?<?php echo $_SERVER['QUERY_STRING']; ?>">

Or use an hidden input field:

<input type="hidden" name="code" value="<?php echo $_SERVER['QUERY_STRING']; ?>" />

But in this last case, then check for $_POST['code'] instead of $_GET['code'].

Or, if you're using $_SESSION:

<?php

    session_start();
    $_SESSION['code'] = $_GET['code'];

be sure to start it also in the receiving script, and check for $_SESSION['code'] instead of $_GET['code']:

<?php

    session_start();

    if(array_key_exists('code', $_SESSION))
    {
        # code here ...

This:

$check_cod=mysql_real_escape_string($_GET['code']);
$check_code=$_SESSION['$check_cod'];

is wrong, for different reasons:

  1. single quotes will not process the variable, so you don't get the value but an index key literally named $check_cod;
  2. you probably don't want to use the variable value as index key of your session, otherwise an attacker could try to pull out some information about a user session, submitting arbitrary index keys.

If you have problems, please share the form you're using to update the password. Bye!

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, change your javascript to:

element1.name="chk[]";
element2.name="txt[]";
element3.name="qty[]";

that will generate this structure:

Array
(
    [chk] => Array
        (
            [0] => on
            [1] => on
            [2] => on
        )

    [txt] => Array
        (
            [0] => item 1
            [1] => item 2
            [2] => item 3
        )

    [qty] => Array
        (
            [0] => 17
            [1] => 34
            [2] => 23
        )

    [submit] => Submit
)

And it should work fine.

ms061210 commented: Thank you very much! It Works! +1
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, can you show the form?

Looking at the array output, it seems most of the values are under the index key txtbox while only the first is under txt which is the one you're trying to loop:

array(4)
{
    ["txt"]=> array(1)
    {
        [0]=> string(5) "item1"
    }

    ["qty"]=> array(1)
    {
        [0]=> string(1) "2"
    }

    ["txtbox"]=> array(4)
    {
        [0]=> string(5) "item2"
        [1]=> string(1) "3"
        [2]=> string(5) "item3"
        [3]=> string(1) "4"
    }

    ["submit"]=> string(6) "Submit"
}
cereal 1,524 Nearly a Senior Poster Featured Poster

could you explain how the unique key definition works?

A unique index is like a primary key, in both cases it can be composed by a single column or by multiple columns: in the last case it works like a sorted array. For more information and examples check this:

cereal 1,524 Nearly a Senior Poster Featured Poster

The unique index works on the combination of all four columns, so it's the equivalent of the select query proposed by Ancient Dragon, if the key combination does not exists there will be an INSERT, else there will be an update. Check this live example:

Or I'm missing something?

showman13 commented: that is amazing - exactly what I was looking for. Thank You very much. +2
cereal 1,524 Nearly a Senior Poster Featured Poster

Otherwise use INSERT ... ON DUPLICATE KEY UPDATE, you have to create a unique key index:

ALTER TABLE tablename ADD UNIQUE KEY(pg_name,mem_id,ct_year,ct_month);

Then your insert query becomes:

INSERT INTO tablename (pg_name, mem_id, ct_year, ct_month, count) VALUES('page.html', 1, 2014, 7, 1) ON DUPLICATE KEY UPDATE count = count + 1;

Docs:

Bye! :)

cereal 1,524 Nearly a Senior Poster Featured Poster

Do you have write permissions on songs directory?

almostbob commented: I thought its an appropriate Q +13
cereal 1,524 Nearly a Senior Poster Featured Poster

Try by adding a backslash:

mv Abhishek\�_xyz.docx newname.docx

Or with double quotes:

mv "Abhishek�_xyz.docx" newname.docx

Or by using a wildcard:

mv Abhish* newname.docx

By the way which kind of shell are you using? Bash?

cereal 1,524 Nearly a Senior Poster Featured Poster

You're welcome and, please, mark the thread as solved. Bye! :)

cereal 1,524 Nearly a Senior Poster Featured Poster

why is it that i cant anymore upload file.

Hi, it can depend on many factors. How big are these files? The default file size limit for the uploads in PHP is 2MB. Check in your PHP configuration the values of post_max_size, upload_max_filesize and memory_limit:

You can access to this information reading the file php.ini or through phpinfo():

<?php

    phpinfo();

Also try to return the $_FILES array from the upload method, just place the return at the top of the method to output directly the array contents:

Route::post('/upload_file', function()
{
    return "<pre>".print_r($_FILES, true)."</pre>";

    # ... other code ...

}

If it works fine you get:

Array
(
    [upload] => Array
        (
            [name] => userguide.pdf
            [type] => application/pdf
            [tmp_name] => /tmp/phpW1NMHq
            [error] => 0
            [size] => 448075
        )

)

If you get an empty array, then you're probably hitting one of the above limits. And if you check the error log of your web server you will find the occurring error:

[Sat Jun 28 13:30:14 2014] [error] [client 127.0.0.1] PHP Warning:  POST Content-Length of 22982481 bytes exceeds the limit of 20971520 bytes in Unknown on line 0, referer: http://localhost/upload_form

Note: regarding my previous example the table name is not correct, I wrote docs_file instead of doc_files... so if you want to try be aware of this mistake.

cereal 1,524 Nearly a Senior Poster Featured Poster

Wait, how big are these files?

Also, try to download one of these files through a test script, for example:

<?php

# database credentials
$dbhost = 'localhost';
$dbname = 'dbname';
$dbuser = 'dbusername';
$dbpass = 'dbpassword';

try
{
    $db = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e)
{
    echo "<p>".date('Y-m-d G:i:s') . " [ERROR]: " . $e->getMessage() . "</p>\n\r";
    $db = null;
}

$id = $_GET['id'];
$stmt = $db->prepare("SELECT * FROM docs_file WHERE docs_id = :id limit 1");
$stmt->execute(array(':id' => $id));

$row = $stmt->fetch(PDO::FETCH_ASSOC);

header('Content-type: '. $row['mimetype']);
header('Content-length: '. $row['size']);

echo $row['data'];

Save it as getfile.php in /public/ and then from the browser call:

http://localhost/getfile.php?id=1

If it still does not work, for example returns file corrupted, open the web developer console, it should open by pressing CTRL + SHIFT + J in Google Chrome, select the Network tab and reload the link, it will appear something like this:

getfile.php?id=1

right click on it and select Copy Response Headers, you should get something like this:

HTTP/1.1 200 OK
Date: Fri, 27 Jun 2014 15:47:27 GMT
Server: Apache
Content-Length: 334549
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/pdf

A better tool to debug these kind of scripts is httpie, if you want to try:

Or Postman, an extension for Google Chrome:

Both will return also the body response and if there is an error in the code, you will see it, for example:

Notice: Undefined index: data …
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, can you show some example data and the table structure?

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, the variable $data is used for the binary data not for the file name, so change the line 4:

$data = $file[0]->filename;

to:

$data = $file[0]->data;

And it should work fine.

cereal 1,524 Nearly a Senior Poster Featured Poster

what 200 stands for on the get file function.

200 is the HTTP status used for successful HTTP requests, for more information check:

I suppose there is some broken data in your table, because of the previouses tests. Could you truncate the table and start some new uploads? Use:

truncate table docs;

This will delete all the previous rows. If, after doing this operation, it doesn't work, please share your updated and working code, related to your updated database table.

cereal 1,524 Nearly a Senior Poster Featured Poster

If you use:

$config['sess_encrypt_cookie']  = TRUE;
$config['sess_use_database']    = TRUE;

And create a session table:

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
    session_id varchar(40) DEFAULT '0' NOT NULL,
    ip_address varchar(45) DEFAULT '0' NOT NULL,
    user_agent varchar(120) NOT NULL,
    last_activity int(10) unsigned DEFAULT 0 NOT NULL,
    user_data text NOT NULL,
    PRIMARY KEY (session_id),
    KEY `last_activity_idx` (`last_activity`)
);

The session cookie will store only this information:

  • session_id
  • ip_address
  • user_agent
  • last_activity

And the cookie will be encrypted with mcrypt, up to version 2.1.4 if mcrypt was not available then they used the _xor_encode() method:

function encode($string, $key = '')
{
    $key = $this->get_key($key);

    if ($this->_mcrypt_exists === TRUE)
    {
        $enc = $this->mcrypt_encode($string, $key);
    }
    else
    {
        $enc = $this->_xor_encode($string, $key);
    }

    return base64_encode($enc);
}

In version 2.2.0 the _xor_encode() method was removed and the encode method now works like this:

function encode($string, $key = '')
{
    $key = $this->get_key($key);
    $enc = $this->mcrypt_encode($string, $key);

    return base64_encode($enc);
}

and in constructor they check if mcrypt is available:

public function __construct()
{
    $this->CI =& get_instance();
    $this->_mcrypt_exists = ( ! function_exists('mcrypt_encrypt')) ? FALSE : TRUE;

    if ($this->_mcrypt_exists === FALSE)
    {
        show_error('The Encrypt library requires the Mcrypt extension.');
    }

    log_message('debug', "Encrypt Class Initialized");
}

If not the Encrypt class won't start.

Ref:

Custom data, instead, will be saved in ci_sessions.user_data. So you never reach the 4KB limit for the session cookie and you can save more data.

Now, having mcrypt enabled is sufficient, but …

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, check /app/config/app.php to be sure that debug is set to true then, if this is still your table structure:

CREATE TABLE docs (
    gov_docs_id int(11) NOT NULL AUTO_INCREMENT,
    personnel_id int(11) DEFAULT NULL,
    docs_name varchar(255) DEFAULT NULL,
    docs_num int(11) DEFAULT NULL,
    docs_date datetime DEFAULT NULL,
    filename varchar(255) DEFAULT NULL,
    data longblob,
    PRIMARY KEY (gov_docs_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Change it, to add the columns size and mime, just run these commands in a MySQL client:

alter table docs add size int unsigned not null default 0;
alter table docs add mime varchar(255) not null;

Then change your code to:

Route::get('/getfile/{id}', function($id)
{
    $file = DB::select('SELECT * FROM docs WHERE gov_docs_id = ?', array($id));
    $data = $file[0]->file;
    return Response::make($data, 200, array('Content-type' => $file[0]->mime, 'Content-length' => $file[0]->size));
});

In order to work fine you have to change also the script used to save the file to the database and add the mine and size columns:

$mime = Input::file('upload')->getMimeType();
$size = Input::file('upload')->getSize();

DB::table('docs')->insert(array(
    'doc_attachment'=> $data,
    'mime' => $mime,
    'size' => $size
    )
);

Remember to change tablename to your current table name (i.e. docs), and also refer to the correct id, which in your table is gov_docs_id. If the problem persists check che error log in /app/storage/logs/ and Apache error log.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, what kind of error you get?

cereal 1,524 Nearly a Senior Poster Featured Poster

Line 36:

<?}?>

change it to:

<?php } ?>

Or to:

<? } ?>

In practice provide some space.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, remove the curly bracket } at line 8.

cereal 1,524 Nearly a Senior Poster Featured Poster

If you use the method insertGetId(), Laravel will return correctly, basing on the value of the auto_increment column. Docs:

By using Eloquent, instead, change the column name, for example:

$p               = new Personnel;
$p->first_name   = '...';
$p->middle_name  = '...';
$p->last_name    = '...';
$p->save();
$p->personnel_id; // <- last inserted id

It should work fine.

here is my schema do i need to array all of this ?

Sorry, I do not understand. :)

cereal 1,524 Nearly a Senior Poster Featured Poster

Are you using Eloquent? If yes, right after you save something call the id property, for example:

$post        = new Post;
$post->title = 'Title';
$post->body  = 'Bla bla bla...';
$post->save();

$post->id; // <- last inserted id

Otherwise use the insertGetId() method:

$id = DB::table('users')->insertGetId(
    array('email' => 'john@example.com', 'votes' => 0)
);

As suggested here: http://laravel.com/docs/queries#inserts

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, then how this should work?

Route::get('/getfile/{id}', function($id)
{
    $file = DB::select('SELECT * FROM docs  WHERE gov_docs_id = ?', array($id = Input::get('id')) 
    $data = $file[0]->file;
    return Response::make( $data, 200, array('Content-type' => $file[0]->mime, 'Content-length' => $file[0]->size));
});

In your table the columns mime and size used as parameters in the response are missing, so the current code will return an error.

Pay attention to the last line of the above script:

return Response::make( $data, 200, array(
    'Content-type' => $file[0]->mime,
    'Content-length' => $file[0]->size)
    );

Where the first argument is the blob data, the second argument is the HTTP status (in this case 200) and the third argument is an array with the headers to send with the response: in this case

Content-type is important and it is used to define the type of data you're sending back to the browser, if it is a PDF the mime will be application/pdf, if docx the mime is:

application/vnd.openxmlformats-officedocument.wordprocessingml.document

And so on for each file-type you want to allow in your database.

Content-length is used to send the size of the file.

You should define this information.

As I previously suggested, check my first example, since there I'm already saving this information, otherwise you have to compute them each time you try to download a file.

Also, saving a file directly into a database is not always a good idea, it would be better to save only the filename. But it's your choice.

cereal 1,524 Nearly a Senior Poster Featured Poster

Can you show your table structure? In a MySQL client run:

show create table docs;

And post the results here. The problem can depend on the data saved in the database table: truncated because of the column type, or it can depend on the system used to define the mime type you are assigning to the downloaded file.

If you can post also few rows from the database, just to see how you're saving the data, could be helpful.

cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, at line 10 use mysqli_error():

if ( ! $result = mysqli_query($con, $query)) {
    printf("Errormessage: %s\n", mysqli_error($con));
}

It should explain the reason that makes the query return boolean FALSE.

Docs: http://php.net/manual/en/mysqli.error.php

cereal 1,524 Nearly a Senior Poster Featured Poster

Yes, in the viewlist, replace the previous loop with a table, for example:

<?php if($id) { ?>
<table>
    <thead>
        <tr>
            <th>Filename</th>
            <th>Data</th>
        </tr>
    </thead>
    <tbody>
        <?php
        foreach($id as $sid)
        {
            echo "
            <tr>
                <td>
                    $sid->name
                </td>
                <td>
                    <button type=\"button\" onclick=\"javascript:location.href='/getfile/$sid->id'\">download</button>
                </td>
            </tr>
            ";
        }
        ?>
    </tbody>
    <tfoot>
        <tr>
            <td></td>
        </tr>
    </tfoot>
</table>
<?php } // end if ?>
cereal 1,524 Nearly a Senior Poster Featured Poster

So, I see:

  1. a view to display the buttons in which you want to load the links to get the files
  2. a controller to save the file
  3. and another to download it.

What is missing is the method from which you will list all the files, for example:

Route::get('/listfiles')
{
    $data['id'] = DB::select("SELECT * FROM tablename");
    return View::make('viewlist', $data);
}

The view viewlist.php:

<html>
    <head>
        <title>List of files</lists>
    </head>
    <body>
        <?php
            foreach($id as $sid)
            {
                echo "
                <input type=\"submit\" onclick=\"javascript:location.href='/getfile/{$sid}'\" />
                ";
            }
        ?>
    </body>
</html>
cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, it will be easier to help you if we can see the controller from which you load the ids of all the files uploaded, for example you're probably using something like:

$data['id'] = DB::select("SELECT * FROM tablename");
return View::make('viewlist', $data);

The DB::select() will return an array, so the above code will translate to:

onclick="javascript:location.href='/getfile/Array'"

To get all the ids you have to use a foreach loop:

@foreach($id as $sid)
    <input type="submit" onclick="javascript:location.href='/getfile/{{{$sid}}}'" />
@endforeach

If you're not using Blade (the templating engine), then the correct code is:

<?php

    foreach($id as $sid)
    {
        echo "
        <input type=\"submit\" onclick=\"javascript:location.href='/getfile/{$sid}'\" />
        ";
    }

?>
cereal 1,524 Nearly a Senior Poster Featured Poster

Good! Are you using Blade? If yes then the id must be $id and surrounded at least from two consecutive curly brackets, three if you want also to sanitize the variable, for example:

/getfile/{{{$id}}} # with Blade

Regarding the onclick attribute, it should work if you try:

onclick="javascript:location.href='/getfile/{{{$id}}}'"
cereal 1,524 Nearly a Senior Poster Featured Poster

by the way i tried to look at my database and i saw that the files i've been stored was convert to .TMP ?

Or you're trying to get the extension from getRealPath()? For the extension use:

$ext = Input::file('upload')->getClientOriginalExtension();
cereal 1,524 Nearly a Senior Poster Featured Poster

No, you're still saving the path and the file name which is the temporary name given by the $_FILES array. In your previous code, you wrote only:

$data = fread(Input::file('file')->getRealPath());

Which is wrong if you do not use also fopen() & co. I supposed you were posting dimostrative code, so read the documentation for fread() or use file_get_contents() as in my example.

i already put this on my route do i need to map this on my onclick button ?

Show your code, please.

Docs:

cereal 1,524 Nearly a Senior Poster Featured Poster

Try this in your router.php file:

Route::get('/getfile/{id}', function($id)
{
    $file = Attachment::find($id);
    $data = $file->doc_attachment;
    return Response::make($data, 200, array('Content-type' => $file->mime, 'Content-length' => $file->size));

});

Again, if you're not using Eloquent, then use DB::select() which returns an array, so it would look like this:

Route::get('/getfile/{id}', function($id)
{
    $file = DB::select('SELECT * FROM tablename WHERE id = ?', array($id));
    $data = $file[0]->file;
    return Response::make($data, 200, array('Content-type' => $file[0]->mime, 'Content-length' => $file[0]->size));

});

I suggest you to save the mime-type and the file size while uploading the file, look at my first example, otherwise you have to declare it in someway.

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, I'm assuming your form is using the enctype attribute, correct?

<form method="post" enctype="multipart/form-data" action="/upload_file">

Otherwise the file will not be uploaded. Also the name attribute in your input field is upload not file (as in my example), so your code becomes:

Input::file('upload')->getRealPath())

To be sure, you should always validate the form request, or at least use:

if(Input::hasFile('upload'))
{
    // save data
}

else
{
    // reject
}
cereal 1,524 Nearly a Senior Poster Featured Poster

Can you show the form and your updated code? Also which version of Laravel are you using?

cereal 1,524 Nearly a Senior Poster Featured Poster

Use Input::file('file') instead of Input::get('file'), the file() method gives you access to the $_FILES array.

After doing this you need to read the contents from the path of the temporary file created by PHP while uploading the file, which is given by the method getRealPath(). To read the binary data, you can use PHP functions like file_get_contents() or fread(), for example:

file_get_contents(Input::file('file')->getRealPath());

In your case, this should work:

$data = file_get_contents(Input::file('file')->getRealPath());
DB::table('tablename')->insert(array(
    'doc_attachment'=> $data
    )
);

But doc_attachment needs to be a blob column type, blob it self can store up to 65KB; if the files are big, then use mediumblob capable of 16MB of storage.

cereal 1,524 Nearly a Senior Poster Featured Poster

Do you want to save the files or only the names? In the former case then use something like this:

<form method="post" enctype="multipart/form-data" action="/upload_file">
    <input type="file" name="file" />
    <input type="submit" name="submit" value="upload" />
</form>

And these methods in the router.php file:

Route::get('/upload_form', function()
{
    $data['files'] = Attachment::get();
    return View::make('uploads.form', $data);

});

Route::post('/upload_file', function()
{

    $rules = array(

        'file' => 'required|mimes:doc,docx,pdf',

        );

    $validator = Validator::make(Input::all(), $rules);

    if($validator->fails())
    {
        return Redirect::to('/upload_form')->withErrors($validator);
    }

    else
    {
        if(Input::hasFile('file'))
        {
            $f = Input::file('file');
            $att = new Attachment;
            $att->name = $f->getClientOriginalName();
            $att->file = base64_encode(file_get_contents($f->getRealPath()));
            $att->mime = $f->getMimeType();
            $att->size = $f->getSize();
            $att->save();

            return Redirect::to('/upload_form');
        }
    }

});

I'm assuming the usage of a model Attachment and a table schema like this:

CREATE TABLE `attachments` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `file` longblob NOT NULL,
  `mime` varchar(255) DEFAULT NULL,
  `size` int(10) unsigned NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `deleted_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

If you still have problems show us your code. Bye.

Sikander Nasar commented: This is not a good approach to write logic in route file +0
cereal 1,524 Nearly a Senior Poster Featured Poster

Have you tried upper()? Example:

select UPPER(CONCAT('CMRC', LPAD(UUID(), 10, '0')));
cereal 1,524 Nearly a Senior Poster Featured Poster

It means $grupa_select (which was $grupa_select2 in your original script) is not defined.

cereal 1,524 Nearly a Senior Poster Featured Poster

Ok, mysql_query() accepts two parameters, the first is mandatory, the second is optional. This:

$pregled = mysql_query("select * from koncerti where grupa_id = ".$grupa_id['id']."");
if (!mysql_query($pregled,$grupa_id,$selektovanje))
{
    die('Error: ' . mysql_error());
}

Should be:

$pregled = mysql_query("select * from koncerti where grupa_id = ".$grupa_id['id']) or die(mysql_error());

Note that at the end of the query I removed the double quotes, that's the reason of the second error:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near " at line 1

If you need quotes because the value to compare is a string then write:

$pregled = mysql_query("select * from koncerti where grupa_id = '" . $grupa_id['id'] . "'");

Spot the difference:

grupa_id = '" . $grupa_id['id'] . "'"

Instead of:

grupa_id = " . $grupa_id['id'] . ""
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, define the error you get on line 42 and add mysql_error() to this query and to the previous.

cereal 1,524 Nearly a Senior Poster Featured Poster

Try to use the row() method:

$row = $cnt->row();
$new_cnt = $row->Counter_field + 1;

But you could also run a single query:

$this->db->query("UPDATE Job_Description SET Counter_field = Counter_field + 1 WHERE id = ?", array($id));

Docs:

ravi142 commented: @Cereal : Thank You. +1
cereal 1,524 Nearly a Senior Poster Featured Poster

@jKidz

can you explain more please?

ok, if you open a conditional statement, before going to the next condition, you need to declare where you want to stop the execution of the code, you can do this by using a semicolon:

$num = rand(0,1);

if($num == 0)
    echo "empty";
else
    echo "not empty";

But in this case you cannot use more than a line of code for each condition. Then you can use colon:

if($num == 0):
    echo "empty";
else:
    echo "not empty";
endif;

But it's not much used. When you use parentheses it looks like:

if($num == 0)
{
    echo "empty";
}

else
{
    echo "not empty";
}

Now if you add a loop:

if($num == 0)
{
    echo "empty";

    while(true)
    {
        echo " loop";
        break;
    }

} // <-- this was missing in your code

else
{
    echo "not empty";
}

Pritaeas suggested you to align the curly brackets, because indenting correctly your code, helps to read and find problems easily.

Read:

@Sikander

you have to use the folder name.this is only work in css.

Hi, not correct, you can use relative paths in PHP and also with the include() function:

Bye!

jKidz commented: amazing bro +0
cereal 1,524 Nearly a Senior Poster Featured Poster

At line 17 you're closing the paranthesis of the while loop, so add another one:

    } // close while loop

} // close if

else {
jKidz commented: great +1
cereal 1,524 Nearly a Senior Poster Featured Poster

It seems you want to search and replace a string in a json encoded array, correct? If yes, then each element is probably surrounded by quotes, example:

$a['blog'] = 'blogtitle';
echo json_encode($a);

// outputs {"blog":"blogtitle"}

Which is different from {blog:blogtitle}, the correct code should be:

if($blogname != "")
{
    $r = str_replace('{"blog":"blogtitle"}', '', $content);
}
else
{
    $r = str_replace('{"blog":"blogtitle"}', $blogname, $content);
}

echo $r;
cereal 1,524 Nearly a Senior Poster Featured Poster

Hi, you can use substr():

<?php

$reportID = 'MPS141';

echo substr($reportID, 5);

Will return all the characters after MPS14, but you can also create a function to return an array of all the elements of the reportID, an example:

function reportToArray($id)
{
    $data['CompanyName']    = substr($id, 0, 2);
    $data['Article']        = substr($id, 2, 1);
    $data['Year']           = substr($id, 3, 2);
    $data['ID']             = substr($id, 5);
    return $data;
}

print_r(reportToArray($reportID));

Returns:

Array
(
    [CompanyName] => MP
    [Article] => S
    [Year] => 14
    [ID] => 1
)

Docs: http://www.php.net/manual/en/function.substr.php

jKidz commented: thanks buddy +0
cereal 1,524 Nearly a Senior Poster Featured Poster

maybe i could do this with aliases?

Hmm, no, because the ErrorLog directive can be set only once for each domain. The easiest solution is to create subdomains for each website and configure indipendent directives.

The CustomLog is used to trace the requests to the server, so it's the access log, you could use an environment variable to trace each website and assign indipendent custom logs, check:

Not tested, but something like this in server or virtual context, should work:

<Directory site1>
    SetEnv subwebsite1
</Directory>

<Directory site2>
    SetEnv subwebsite2
</Directory>

CustomLog ${APACHE_LOG_DIR}/site1.log combined env=subwebsite1
CustomLog ${APACHE_LOG_DIR}/site2.log combined env=subwebsite2
cereal 1,524 Nearly a Senior Poster Featured Poster