errors not showing - file-upload

I have an issue with my php photo upload script. When I upload a file that exceeds 2mb, it won't show that error when I click upload..yet it's there in my script..any idea why this is? For ex. I uploaded a .wma file and It was 2.38MB..that exceeds the limit..but yet it just says "file type not allowed" why didn't it show the exceeds 2mb error as well?
Here is my script:
<?php
include 'init.php';
if(!logged_in()){
header('Location: index.php');
exit();
}
include 'template/header.php';
?>
<h3>Upload Image</h3>
<?php
if(isset($_FILES['image'], $_POST['album_id'])){
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_temp = $_FILES['image']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$image_ext = strtolower(end(explode('.', $image_name)));
$album_id = $_POST['album_id'];
$errors = array();
if (empty($image_name) || empty($album_id)){
$errors[] = 'Something is missing';
} else {
if(in_array($image_ext, $allowed_ext) === false){
$errors[] = 'File type not allowed';
}
if($image_size > 2097152){
$errors[] = 'Maximum file size is 2MB';
}
if(album_check($album_id) === false){
$errors[] = 'Couldn\'t upload to that album';
}
}
if(!empty($errors)){
foreach ($errors as $error){
echo $error, '<br />';
}
} else {
// upload image
}
}
$albums = get_albums();
if(empty($albums)){
echo '<p>You don\'t have any albums. Create an album</p>';
} else {
?>
<form action="" method="post" enctype="multipart/form-data">
<p>Choose a file:<br /><input type="file" name="image" /></p>
<p>
Choose an album:<br />
<select name="album_id">
<?php
foreach ($albums as $album){
echo '<option value="', $album['id'], '">', $album['name'], '</option>';
}
?>
</select>
</p>
<p><input type="submit" value="Upload" /></p>
</form>
<?php
}
include 'template/footer.php';
?>
Thanks again for all of the patience with my probably easy posts for a lot of you more experienced programmers out there!
-TechGuy24

As per code, it should, if uploaded file size is >2mb. However, computers never make mistake but the human and thus debugging is important.
Just replace the code
if($image_size > 2097152){
$errors[] = 'Maximum file size is 2MB';
}
with debug statements
if($image_size > 2097152){
echo "in if, image size=".$image_size;
$errors[] = 'Maximum file size is 2MB';
} else {
echo "in else, image size=".$image_size;
}
This is just a first step of debugging. It may or may not fix the real cause. Let us know the output.
Edit after comment:
Put that code in the starting of the file.
echo "files<pre>";
print_r($_FILES);
echo "</pre>imgsz=".$_FILES['image']['size'];
What is the output. I guess it might include
[error] => 1
If it show error=1, Check http://php.net/manual/en/features.file-upload.errors.php
That mean your upload_max_filesize in php.ini is set to 2MB or less. As soon as person upload file bigger than that, it never reach your code as PHP reject the file by default.
To fix that, open php.ini and increase the limit of upload_max_filesize.
Edit 3 after comment
Change
if($image_size > 2097152){
to
if($_FILES['image']['error']==1){
That will fix the issue.

Related

php redirect when idle not redirecting

I found the following script at https://thisinterestsme.com/expire-php-sessions.
This code is used to check if user is inactive for a period
logout and direct to login screen.
problem
Redirect does not happen. Redirect happens only when page is refreshed.
script
<!-- language: lang-html -->
<?php $inactive = 30;
$_SESSION['inactive']=$inactive;
if( !isset($_SESSION['timeout']) )
$_SESSION['timeout'] = time() + $inactive;
$session_life = time() - $_SESSION['timeout'];
$_SESSION['life']=$session_life;
if ($session_life > $inactive)
{ session_destroy();
echo '<script>';
echo 'console.log("You have been logged-out!");';
echo 'window.location.href="login.php"';
echo '</script>';
}
$_SESSION['timeout']=time();
?>
Redirect happens only when I refresh the page
instead of echo 'window.location.href="login.php"' I triedheader("Location: login.php") but no success (NO auto redirect to "login" page ).
What shall I do so that the page will be redirected without refresh?
I am using PDO+ php 7
I found a thread and tried this:
<meta http-equiv="refresh" content="900;url=login.php" />
But this does not check whether "idle" or NOT.
Thanks in advance
I wish to share the complete answer.
Check whether idle for 30 seconds (15 minutes). If yes (idle for 30 seconds) destroy the session. Here's a code snippet to be cut and paste on top of web page:
<?php
session_start();
if (!isset($_SESSION['loginid']))
{
header("Location: login.php");
}
// store inactive time
$inactive = 30;
$_SESSION['inactive']=$inactive;
if( !isset($_SESSION['timeout']) )
$_SESSION['timeout'] = time() + $inactive;
$session_life = time() - $_SESSION['timeout'];
$_SESSION['life']=$session_life;
if ($session_life > $inactive)
{ session_destroy();
unset($_SESSION['loginid']);
header("Location: login.php");
}
$_SESSION['timeout']=time();
?>
Check whether idle for more than 30 seconds. Here's jQuery code (cut and paste in common sharing file normally used with Include_once("xxxx.php").
$(function(){
function refreshDiv(){
$.ajax({
url: 'checkidletime.php'
}).done(function(result) {
$('#refreshDIV').html(result);
window.setTimeout(refreshDiv, 5000);
});
}
window.setTimeout(refreshDiv, 5000);
});
Checkidletime.php called by above function refreshDiv (part of include file):
session_start();
$session_life = time() - $_SESSION['timeout'];
if ($session_life > $_SESSION['inactive'] )
{ unset($_SESSION['loginid']);
?>
<script>
location.reload();/* refresh page
</script>
<?php
}

Passing variables to fpdf

I have a problem with passing variables to fpdf. First script is getting post text sent to filtering class, the class is returning filtered POST-s as a 2 element array. First script looks like this:
include('service.php');
include('pdf.php');
$pdf_filter = new Pdf_filter;
$filter = $pdf_filter->pdfFilter();
var_dump($filter);
extract($filter);
I'm extracting $filter array to get variables from it (filtering script is creating variables of the POST that are sent and I can echo them so I don't know if this is even necessary).
The second script looks like this:
require('E:\Xampp\php\fpdf181\fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',12);
$pdf->Cell(195,5, $tytul, 0,1,'C');
$pdf->Cell(195,5, $petycja, 0,1,'C');
$pdf->Output();
and I'm getting this error:
Notice: Undefined variable: tytul in E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\pdf.php on line 10
Notice: Undefined variable: petycja in E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\pdf.php on line 11
Fatal error: Uncaught exception 'Exception' with message 'FPDF error: Some data has already been output, can't send PDF file' in E:\Xampp\php\fpdf181\fpdf.php:271
Stack trace: #0 E:\Xampp\php\fpdf181\fpdf.php(1063): FPDF->Error('Some data has a...')
#1 E:\Xampp\php\fpdf181\fpdf.php(999): FPDF->_checkoutput()
#2 E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\pdf.php(12): FPDF->Output()
#3 E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\test.php(3): include('E:\\Xampp\\htdocs...')
#4 {main} thrown in E:\Xampp\php\fpdf181\fpdf.php on line 271
How should I pass the variables? Interesting: it works if I use the unfiltered $_POST with the following code:
require('E:\Xampp\php\fpdf181\fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',12);
$pdf->Cell(195,5, $_POST['tytul'], 0,1,'C');
$pdf->Cell(195,5, $_POST['petycja'], 0,1,'C');
$pdf->Output();
EDIT: I will post the initial form and filtering function:
Form:
<form action="test.php" method="POST">
Wpisz tytuł petycji (35 znaków):<br>
<input type="text" name="tytul" maxlength="35" size="35" placeholder="Tytuł petycji" required><br>
Wpisz treść petycji (500 znaków):<br>
<textarea name="petycja" maxlength="500" rows="4" cols="50" placeholder="Treść petycji" required></textarea><br>
<input type="submit" value="Napisz petycje">
</form>
Filtering function:
class Pdf_filter{
protected $title;
protected $text;
public function pdfFilter(){
if (isset($_POST)){
foreach ($_POST as $key => $val) {
$filterVal = strip_tags($val);
$filterVal = htmlspecialchars($filterVal);
$filterVal = stripslashes($filterVal);
$filterVal = str_replace("\\", "", $filterVal);
$filter = array($key => $filterVal);
foreach ($filter as $key => $val) {
echo "[$$key]";
echo "$val<br>";
${$key} = $val;
}
}
if(!preg_match("/^[\sa-zA-ZĄĆĘŁŃÓŚŹŻąćęłńóśźż0-9-_,.:\'?()]+$/", $tytul)){
echo "Niedozwolone znaki $tytul!";
exit();
}
elseif(!preg_match("/^[\sa-zA-ZĄĆĘŁŃÓŚŹŻąćęłńóśźż0-9-_,.:\'?()]+$/", $petycja)){
echo "Niedozwolone znaki $petycja!";
exit();
}
else{
return $filter = array('tytul'=>$tytul,'petycja'=>$petycja);
}
}
else{
echo "Proszę wypełnić wszytskie pola!";
}
}
}
Well I am dumb. The problem was related with class variables. Code that happened to work for me:
class Pdf extends FPDF{
protected $filter;
protected $tytul;
protected $petycja;
public function __construct($filter){
$this->filter = extract($filter);
$this->tytul = $tytul;
$this->petycja = $petycja;
}
public function tytul(){
return $this->tytul;
}
public function petycja(){
return $this->petycja;
}
public function dokument(){
parent::__construct();
$this->AddPage();
$this->SetFont('Arial','B',15);
$this->Cell(195,5, $this->tytul, 0,1,'C');
$this->Cell(195,5, $this->petycja, 0,1,'C');
$this->Output();
}
}
Now I need to think of a way to display polish symbols in fpdf and line breaks (but that maybe done with text editor isntead of just textbox).

Simple Yahoo Weather Api Not Working

I was using a simple code which includes a yahoo api code to get just the weather from my city and put in on my web page, however, i just read that yahoo public api is no longer working and i dont know how can a i get this code to work, i have a yahoo account, i created an api and i dont know how to proceed since here. If somebody can help me this is the code:
<?php
/*Clima*/
if(isset($_POST['zipcode']) && is_numeric($_POST['zipcode'])){
$zipcode = $_POST['zipcode'];
}else{
$zipcode = 'ARMA0056';
}
$result = file_get_contents('http://weather.yahooapis.com/forecastrss?p=' . $zipcode . '&u=c');
$xml = simplexml_load_string($result);
//echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$xml->registerXPathNamespace('yweather', 'http://xml.weather.yahoo.com/ns/rss/1.0');
$location = $xml->channel->xpath('yweather:location');
if(!empty($location)){
foreach($xml->channel->item as $item){
$current = $item->xpath('yweather:condition');
$forecast = $item->xpath('yweather:forecast');
$current = $current[0];
$clima = <<<END
<span>{$current['temp']}°C</span>
END;
}
}else{
$clima = '<h1>No results found, please try a different zip code.</h1>';
}
/*Clima*/
?>
just replace http://weather.yahooapis.com with http://xml.weather.yahoo.com. credits to https://forum.rainmeter.net/viewtopic.php?f=13&t=23010
xml.weather.yahoo.com was the solution, but the URL does not seem to be working anymore. Im now using yahoos query to get the XML i.e."https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2489314"
This seems to be the same XML with the exception of "results" added to the tree.
Yahoo recently updated the way they handle requests. It used to be just over any connection, but now to make it more secure and easier to handle, they recently opted into sending all requests over OAuth1. Use the sample code they provide on their page and get the information from the request over JSON.
See https://developer.yahoo.com/weather/ for more information.
YAHOO changed some rules about api;
I made following class working for me... hope works for you;
$fcast=$phpObj->query->results->channel->item->forecast; change this line for other items...
<?php
date_default_timezone_set('CET');
class weatherfc{
public $result;
function weather($city){
$BASE_URL = "http://query.yahooapis.com/v1/public/yql";
$yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="'.$city.'") and u="c"';
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
// Make call with cURL
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
//var_dump($phpObj);
$weatherd='<div> Weather In '.$city.'<br>';
$fcast=$phpObj->query->results->channel->item->forecast;
foreach($fcast as $witem){
$fdate=DateTime::createFromFormat('j M Y', $witem->date);
$weatherd.= '<div class="days">';
$weatherd.= '<div class="item"><div>'.$fdate->format('d.m').' '.$witem->day.'</div><div class="image" style="width:90px !important; height:65px !important;"><img src="http://us.i1.yimg.com/us.yimg.com/i/us/nws/weather/gr/'.$witem->code.'d.png" width=90></div></div>';
$weatherd.= '<div><span>'.$witem->high.'°C</span>';
$weatherd.= '<span>'.$witem->low.'°C</span></div></div>';
};
$this->result=$weatherd;
}
}
$h= new weatherfc;
$h->weather("Antalya,Turkey");
echo $h->result;
?>
<style>
.days{
width:90px;
font-size:12px;
float:left;
font-family:Arial, Helvetica, sans-serif;
border:#999 1px dotted;
}
</style>

PHP 5 display mysql table error - Call to undefined function mysql_results()

I premise I'm new to php. I've tried to create a php page that displays the content of a MySQL database. As I try it in localhost I have this warning:
"Fatal error: Call to undefined function mysql_results() in C:\xampp\htdocs\phplessons\guestbook_displayer_2.php on line 18". It seems the db connection works. Someone have a tip?
This is my code:
<html>
<head></head>
<title>Display MySQL db</title>
<body>
<?php
$db=mysql_connect("localhost","root","mypassword"); //db connection
mysql_select_db ("prova001"); //choose a db
$res=mysql_query("SELECT * from php_guestbook"); //query a table
$num=mysql_num_rows($res);
// begin table
echo "<table border=1>";
echo "<tr><td>Nr.</td><td>First name</td>";
echo"<td>Last name</td><td>Country</td>";
echo"<td>E-Mail address</td><td>Telephone</td></tr>";
// contatore
for ($i=0; $i<$num; $i++)
{
$cg=mysql_results($res,$i,"firstname"); // line 18 this var is undefined.
$nm=mysql_results($res,$i,"lastname"); //Probably also the others have a similar problem.
$np=mysql_results($res,$i,"country"); //Can it be due to a bad record counter?
$st=mysql_results($res,$i,"email");
$tl=mysql_results($res,$i,"telephone");
$lf=$i+1;
//
echo "<tr><td>$lf</td><td>$cg</td><td>$nm</td><td>$np</td><td>$st</td><td>$tl</td></tr>";
}
echo "</table>";
mysql_close($db);
?>
</body>
You have probably made a typo. The method is mysql_result() without 's'.
But, you can shorten your query result handling by this way ;
// query
$res=mysql_query("SELECT * from php_guestbook"); //query a table
// begin table
echo "<table border=1>";
echo "<tr><td>Nr.</td><td>First name</td>";
echo"<td>Last name</td><td>Country</td>";
echo"<td>E-Mail address</td><td>Telephone</td></tr>";
while ($item = #mysql_fetch_assoc($res)) {
// do something with var $item;
$cg = $item['firstname'];
$nm = $item['lastname'];
// ect
}

Check from theme's .tpl file for enabled module?

How can I check in theme's .tpl file with "If" operator is there enabled module(s) in a certain hook?
{if !empty($hook_name)}
{$hook_name}
{/if}
I do not still find any reason to do this checking. But anyway, there is a solution.
Surround your code in template by:
{if $some_modules_enabled}
...
{/if}
And put the below code in a controller, ex: FrontController.php
$id_hook = Hook::get($name_of_the_hook);
$some_modules_enabled = false;
foreach ( Hook::getModulesFromHook($id_hook) as $row ) {
if ( Module::isEnabled( $row['name'] ) ) {
$some_modules_enabled = true;
break;
}
}
$this->context->smarty->assign('some_modules_enabled', $some_modules_enabled);