getting errors in php coding something undefined variable - javascript

I am getting following error in this code : Strict Standards: Only variables should be passed by reference in C:\xampp\htdocs\uploader\upload.php on line 12
Success
also other error are Notice: Undefined variable: fulltarget in C:\xampp\htdocs\uploader\upload.php on line 101
Notice: Undefined variable: fulltarget in C:\xampp\htdocs\uploader\upload.php on line 101
Here is the pastebin link to see the whole code : http://pastebin.com/JKegmNHC
Also here is the code also available.. you can see it through here or using the pastebin link to get the error indication right from the related line....
Here is the code :
<?php
$submit=$_POST['sub'];
if(isset($submit))
{
$name=$_FILES['img']['name'];
$type=$_FILES['img']['type'];
$size=($_FILES['img']['size'])/1024;
$ext=end(explode('.',$name));
if (($ext == "gif")
|| ($ext == "jpeg")
|| ($ext == "jpg")
|| ($ext =="png")
&& ($size > 30))
{
############################## File Renaming ###################################################
$newname=uniqid();
//$ext=end(explode('.',$name));
$fullname=$newname.".".$ext;
$target="pics/";
$fulltarget=$target.$fullname;
if(move_uploaded_file($_FILES['img']['tmp_name'],$fulltarget))
{
echo "Success";
}
else
{
echo "Failed";
}
############################## File Renaming end ###################################################
}
else{
echo "not successful";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="abhi.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Php Image Uploader</title>
</head>
<body>
<div id="a1">
<form name="frm" method="post" enctype="multipart/form-data">
<input type="file" name="img" /><br />
<input type="submit" name="sub" value="Store" />
</form>
</div>
<div id="a2">
<?php echo "
<html>
<head>
<title>Aviary Photo Editer</title>
<!-- Load Feather code -->
<script type='text/javascript' src='http://feather.aviary.com/js/feather.js'></script>
<!-- Instantiate Feather -->
<script type='text/javascript'>
var featherEditor = new Aviary.Feather({
apiKey: 'ceegvx4siylhayrr',
apiVersion: 3,
theme: 'dark', // Check out our new 'light' and 'dark' themes!
tools: 'enhance,frames,crop,orientation,brightness,saturation,sharpness,draw,redeye,blemish,effects,stickers,resize,focus,contrast,warmth,colorsplash,text,whiten',
appendTo: '',
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
onError: function(errorObj) {
alert(errorObj.message);
}
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
</script>
</head>
<body>
<div id='injection_site'></div>
<img id='image1' src='$fulltarget'/>
<p><input type='image' src='http://images.aviary.com/images/edit-photo.png' value='Edit photo' onclick=\"return launchEditor('image1', '$fulltarget');\" /></p>";
?>
</body>
</html>

As per the [PHP: end - Manual], when you use end() it passes the last element in the array as a reference.
You can try a couple things:
Don't use explode() in end(). Try doing the explode when you declare $name:
$name = explode( '.', $_FILES['img']['name'] );
Use array_slice() and list() instead of end():
list($ext) = array_slice( explode( '.' , $name ), -1 );
Either one would probably work.

You get 'Notice: Undefined variable' errors because you try to use a variable without initializing it first. In your HTML you use '$fulltarget', but it's only set after you submitted the form. If you want to get rid of this notice you should put something like $fulltarget = ''; after your PHP opening tag.
If you will check the PHP end() function documentation http://php.net/manual/en/function.end.php you will see that the function takes an array as a parameter through reference. To fix this error you should save your explode() results as a variable and then pass that variable to end() function. For example: $arr = explode('.', $name); $ext = end($arr);

Related

Pass and print a $_GET variable through php load file by javascript

I searched for a solution of passing a get variable obtained from index.php page to included.php file[ loaded by javascript ]. A nice solution by php require function is given Pass and print a $_GET variable through an included file by php require function
However, in my case I have
for index.php => url[ index.php?var=item]
<?php
if(isset($_GET['var'])) {
$var=$_GET['var'];
}
?>
<script>
$(document).ready(function(){
$("#ok").load("included.php");
});
</script>
<div id='ok'>
</div>
in included.php [which will be loaded in index.php by javascript load function]
<?php
echo $var;
?>
The error was the undefined var in included.php file.How Can I echo this variable with a combination of php and javascript ?
If you want to pass these variables on to the included file you could go with
$("#ok").load("included.php?<?php echo $urlString; ?>");
The URL string can be generated with this function
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
Another option would be :
$( "#ok" ).load( "included.php", { "choices[]": [ "Jon", "Susan" ] } );
Based upon the first example:
index.php:
<?php
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
if(isset($_GET['var']) === true) {
$var=$_GET['var'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Test</title>
<script type="text/javascript">
$(document).ready(function(){
$("#ok").load("included.php?<?php echo GenGetVars(); ?>");
});
</script>
</head>
<body>
<div id='ok'>
</div>
</body>
</html>
included.php
<?php
echo print_r($_GET, true);
?>
index.php:
<?php
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
if(isset($_GET['var']) === true) {
$var=$_GET['var'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Test</title>
<script type="text/javascript">
function LoadScriptFile(){
/// SENDING THE INFORMATION BY AJAX
$.ajax({
type : "POST", /// SEND TYPE
url : "getScriptName.php", /// TARGET FILE TO RETRIEVE INFORMATION
data : {
'SomeParamID' : 1,
'AnotherParamID' : 'Dunno.. just something'
},
///######## IN CASE OF SUCCESS
success:function(response){
if( response != "" ){
$.getScript( 'js/' + response + '.js', function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
}
else{
alert( "Error retreiving data" );
}
}
}
);
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#ok").load("included.php?<?php echo GenGetVars(); ?>");
});
</script>
</head>
<body>
<div id='ok'>
</div>
</body>
</html>
included.php
<?php
echo print_r($_GET, true);
?>
getScriptName.php
<?php
switch($_POST['SomeParamID']){
case 1:
echo 'MyGreatJSFile';
break;
case 2:
echo 'MyNotSoGreatJSFile';
break;
}
?>
You could try this.

how to solve "Uncaught SyntaxError: missing ) after argument list" error

I am working on putting a project and one part of project is retrieving all the data from excel cells into an array for autosuggestion jquery like the one in the autocomplete module link.
So far I achieved to put data from excel into PHP array than convert into JQuery array with help Json_encode and by using flattenArray function all my data is in a single dimensional Array.
Autocomplete function works when my data comes out of an basic excel data which looks like:
however when I put a little bit complicated data like this:
I face of with a problem Uncaught SyntaxError: missing ) after argument list when data goes exactly into my
$(function(){var availableTags = $.parseJSON('<?php echo json_encode($myFlatArray); ?>');
my question how can I prevent this error appearing and autocomplete works fine?
Edit:
here is my code...
<?php
set_include_path(implode(PATH_SEPARATOR, [
realpath(__DIR__ . '/Classes'), // assuming Classes is in the same directory as this script
get_include_path()
]));
require_once dirname(__FILE__) . '/Classes/PHPExcel/IOFactory.php';
require_once 'PHPExcel.php';
$file= "./uploads/".$_GET["filename"];
$inputFileName = ($file);
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
$total=array();
for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// echo "-----------------as rowData---------------";
// var_dump($rowData); // Insert row data array into your database of choice here
// echo "-----------------VAR_DUMP total!---------------";
array_push($total, $rowData);
// var_dump($total);
$myFlatArray = PHPExcel_Calculation_Functions::flattenArray($total);
echo "<br>";
echo "----------------- KOVA as json encode---------------";
var_dump(json_encode($myFlatArray));
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function(){var availableTags = $.parseJSON('<?php echo json_encode($myFlatArray); ?>');
$( "#tags" ).autocomplete({source: availableTags});
});
</script>
</head>
<body>
<br>
<br>
<br>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
<br>
<br>
<br>
<br>
</div>
</body>
</html>

Variable communication from php to javascript both of different pages

I had a variable in my php page which is an URL printed on that page, I had another html page where I needs this URL value from that php page and it should be assigned to the button in html page.
How can it be performed?
php page content:
if ($output== true) {
//Output results as URL
print_r($resulta);
}
html page content:
<p align="center">
<input type="button" name="res1" value="result">
You should use Ajax.
When you need information to be filled in HTML page the only easy way is Ajax.
I suggest you to use jQuery for simpler requests.
More info about making get request with jQuery: https://api.jquery.com/jquery.get/
Example:
$(function() {
$.get('request.php', {}, function(response) {
if (response.url) {
alert('No information from server!');
return;
}
$('button.mybutton').onclick(function() {
window.location.href = response.url;
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mybutton">Click</button>
And in your PHP something like this:
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
$response = json_encode(array( 'url' => $url ));
die($response);
Header "Access-Control-Allow-Origin" is important when you do an Ajax request from different domains. you can see more usages of it in google: Access-Control-Allow-Origin
Use $_GET method to pass variables between PHP pages.
In your PHP page,
<?php
$value = "Some value";
header("location:nextPage.php?variable=$value");
exit();
?>
In the nextPage.php
<?php
$received = $_GET['variable'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<<button type="button"><?php echo $received; ?></button>
</body>
</html>
If the next page is not a PHP file, here is a solution,
// THIS WORKS FOR MULTIPLE VALUES, BUT IF YOU DO NOT SEND ANY VALUES, IT WILL SHOW ERROR OF "UNDEFINED". BUT THAT CAN ALSO BE FIXED.
// EXAMPLE : http://yourdomain.com?tag1=100&tag2=200&tag3=300
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
var url,url_contents,received_values,passed_values;
url = document.URL;
url_contents = url.split("?");
received_values = url_contents[1];
received_values = received_values.split("&");
for(var i=0;i<received_values.length;i++)
{
var value_array = received_values[i].split("=");
alert(value_array[0]+"="+value_array[1]);
}
</script>
</head>
<body>
</body>
</html>

I'm having trouble passing a PHP array to Javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm using PHP and javascript to create a banner function. All of my images are in the folder Images/banners, and are being dynamically added by PHP, and then added to theJavaScript array "adImages". That part is working fine, as I can see the array in the JavaScript when I viewsouce. However, the images are not being placed on the page.
Here is my code, what am I missing?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotating Banners</title>
<?php
$dir = 'Images/banner';
$files = scandir($dir);
array_shift($files);
array_shift($files);
?>
<script language="Javascript" type="text/javascript">
// Setting variables
dir = Images/banner/
adImages = <?php echo json_encode($files); ?>;
thisAd = 0
imgCt = adImages.length
// Rotate function
function rotate() {
if (document.images) {
thisAd++
if (thisAd == imgCt) {
thisAd = 0
}
document.adBanner.src=dir+adImages[thisAd]
setTimeout("rotate()", 1 * 1000)
}
}
</script>
</head>
<body onload="rotate()">
<center>
<img src="" name="adBanner" alt="Ad Banner" />
</center>
</body>
</html>
Seems to work for me after making your dir var a string. Using your Chrome Developer Tools / Console pointed the errors out for you. The following code works for me with two sample images:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotating Banners</title>
<?php
$dir = 'Images/banner';
$files = scandir($dir);
array_shift($files);
array_shift($files);
?>
<script language="Javascript" type="text/javascript">
// Setting variables
var dir = "Images/banner/",
adImages = <?php echo json_encode($files); ?>,
thisAd = 0,
imgCt = adImages.length;
// Rotate function
function rotate() {
if (document.images) {
thisAd++
if (thisAd == imgCt) {
thisAd = 0
}
document.adBanner.src=dir+adImages[thisAd]
setTimeout("rotate()", 1 * 1000)
}
}
</script>
</head>
<body onload="rotate()">
<center>
<img src="" name="adBanner" alt="Ad Banner" />
</center>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="jquery.js"></script>
<?php
$dir = '';
$files = array();
$dir = 'Images/banner';
$aExclusion = array( '..', '.' );
$files = array_diff(scandir($dir), $aExclusion);
$files = array_values( $files );
echo '<script>';
echo "var adImages = [];";
echo 'var oData = ' . json_encode( $files ) . ';';
echo '</script>';
?>
<script>
$(document).ready(function()
{
// Get banner count minus one for array offset.
iBannersSize = Object.keys(oData).length - 1;
// Ensure we have at least 1 banner to rotate.
if( iBannersSize > 0 )
{
window.setInterval(function(){
iChangeToImage = Math.round( Math.random() * ( iBannersSize - 0 ) );
$("div#banner_wrapper img").attr("src", 'Images/banner/' + oData[ iChangeToImage ] );
console.log( oData[ iChangeToImage ] );
}, 2000 );
}
});
</script>
</head>
<body>
<center>
<div id="banner_wrapper">
<!-- Render first banner on page load -->
<img src="<?php echo 'Images/banner/' . $files[ 0 ]; ?>" alt="Ad Banner">
</div>
</center>
</body>
</html>

Checking time of submitting file in form

I want to have a HTML form to send a file to my server by user. I need to know the exact time he started sending this file - not the time that the file was received (I can check received time e.g. by checking file modification time at server). This code should do this - when clicking "Submit" the current server time should be written to logsForSendingForm.txt and when the file receives time should be written to logsForReceivedForm.txt.
Unfortunately, when sending the file, only the time when the file is received is written to logsForReceivedForm.txt - nothing is written to logsForReceivedForm.txt.
What is interesting, if I don't select any file and click Submit, current time is written to both files.
If you don't know how to debug this, but you can suggest any other solution (maybe without AJAX), it's also OK, I don't need to do it like in this code.
<?php
if (isset($_POST['tickStart']))
{
file_put_contents('logsForSendingForm.txt', time() . "\n", FILE_APPEND);
}
elseif (!empty($_FILES))
{
file_put_contents('logsForReceivedForm.txt', time() . "\n", FILE_APPEND);
$f = $_FILES['file'];
$patch = str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME']);
copy($f['tmp_name'], $patch.$f['name']);
}
?><!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-2.1.0.min.js'></script>
<script type='text/javascript'>
function sending()
{
$.ajax({
url: 'index.php',
type: 'POST',
data: { tickStart: true }
});
return true;
}
</script>
</head>
<body>
<form action='index.php' method='post' enctype='multipart/form-data'>
<input type='file' name='file'><br>
<input type='submit' name='submit' value='Submit' onsubmit="return sending()">
</form>
</body>
</html>
There needs to be a bit more checking done on your part, but here is some briefly tested code. I used microtime() instead of time because for small files there is no difference in seconds on my localhost. I also threw in something from here to help inform the user that their file was too big, for example. You might want to catch according to mime-type and inform them of that too...
I threw out Jquery because it seemed superfluous.
You might still get a corrupted file if (and when) multiple clients attempt to write to your logs. (That is why I added the | LOCK_EX flag to your append. I have not done any load-testing, so no guarantees there.) Database???
Otherwise, you'll probably also want to do some filename normalization to get rid of illegal / non-ascii characters. But that's another question that has been treated elsewhere.
Cheers.
EDIT:
duration: 0.084668874740601 (for a 23mb file on localhost)
duration: 0.0021710395812988 (for a 74k file on localhost)
<?php
if (isset($_POST['tickStart']))
{
// this is the moment the script began
$mtime1=$_SERVER['REQUEST_TIME_FLOAT'];
$log = 'sent: ' . $mtime1;
}
if(isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post' && $_FILES['file']['size'] == 0){
$postMax = ini_get('post_max_size');
$fileMax = ini_get('upload_max_filesize');
$message = "Max filesize: $fileMax<br>Max postsize: $postMax";
$log = 'file too large';
}
elseif (!empty($_FILES) && !empty($_POST) && $_FILES['file']['size'] > 0)
{
$f = $_FILES['file'];
$patch = str_replace('index.php', '', $_SERVER['SCRIPT_FILENAME']);
copy($f['tmp_name'], $patch.$f['name']);
// this is the time NOW
$mtime2=microtime(true);
file_put_contents('logsForSendingForm.txt', $mtime1 . "\n", FILE_APPEND | LOCK_EX);
file_put_contents('logsForReceivedForm.txt', $mtime2 . "\n", FILE_APPEND | LOCK_EX);
$duration = $mtime2 - $mtime1;
$log = $log . '\nduration: '.$duration;
$message = $f['name'].' uploaded.';
}
else
{
$log = 'no file selected';
$message = 'Please choose a file.';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script type='text/javascript'>
console.log('<?php print $log ?>');
</script>
</head>
<body>
<form action='index.php' enctype='multipart/form-data' method='POST'>
<input type='file' name='file'><br>
<input type='hidden' value='true' name='tickStart'>
<input type='submit' name='submit' value='Submit'>
</form>
<h2>
<?php print $message; ?>
</h2>
</body>
</html>

Categories