Why is my Javascript not working from the PHP file? - php

I have the following files. For some reason my JavaScript (inside PHP 'echo' tags) does not work:
HTML (index.php):
<form action="submit.php" method="post">
<div id="edit-box">
<INPUT type="submit" name="save-text" id="save-text" value="Save">
<textarea id="editor" name="editor">
<?php echo $content; ?>
</textarea>
</div>
</form>
PHP (submit.php):
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = getRealIPAddress();
if ($content != '') {
mysql_query("INSERT source SET submit_date='$submit_date', ip='$ip_address', content='$content'")
or die(mysql_error());
// The following line is not working! I need help here!
echo '<script type="text/javascript"> alert("Your file saved!");</script>';
mysql_close($connection);
}
?>
The "submit.php" does not have any other PHP or HTML script/tags. I understand I am using obsolete PHP/MySQL API (instead of PDO / MySQLi), but that's beside the point.

It should should print an alert.
Are sure you are printing the script? I can see it might die on an
error in the query.
If that is not the case, what are you including in the connect-db.php,
it might be that somewhere in the required file you are messing up
the output buffer..
Also I'm pretty sure the sql is incorrect:
INSERT source SET submit_date='$submit_date', ip='$ip_address', content='$content'
INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content');
And that is not a secure query, however... that is beside the point.
Here is some more reasons why this could happen:
The include("connect-db.php'); might kill the execution of the script.
If there is something wrong inside of it.
The query might die.
The output is redirected to somewhere else, in the php configuration,
or inside of "connect-db.php"
getRealIPAddress() is not documented, and might cause the script to break.
There might be something bogus in $_POST['editor'] that might break cause
the sql to die.

Try below code
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = getRealIPAddress();
$content = $_POST["editor"];
if ($content != '') {
mysql_query("INSERT source SET submit_date='$submit_date', ip='$ip_address', content='$content'")
or die(mysql_error());
// The following line is not working! I need help here!
echo '<script type="text/javascript"> alert("Your file saved!");</script>';
mysql_close($connection);
}
?>

Related

PHP include make the whole page appear? [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 8 years ago.
Improve this question
Okay, my code is simple:
<?php include 'formvalidation.php';
echo $name; ?>
I want to make only the $name appear, but the whole 'formvalidation.php' shows up.
How can I fix that?
"I want that after I pressed the button, the function I had written will be excute to check the input, and then if the input is right, it'll redirect to another page, which can display the input."
If you wish to redirect after a form has been submitted and show a name afterwards, you will need to use sessions and a header.
Here is an example, (see comments in code) to be added inside formvalidation.php:
<?php
session_start();
// all other codes you already have
$name = "John"; // this is an example
// replace above with your POST variable
// such as $name = $_POST['name'];
$_SESSION['showname'] = $name;
header("Location: your_other_file.php");
exit; // keep this
N.B.: Make sure there is nothing else above <?php session_start(); such as your form, because this will throw a warning, stating Headers already sent...
your_other_file.php
<?php
session_start();
if(isset($_SESSION['showname'])){
$name = $_SESSION['showname'];
echo $name;
}
$name = "John"; // this is an example
Replace above in code with your POST variable.
Such as $name = $_POST['name']; as an example, since you have not provided additional code as to what your superglobal variable is for the name.
You can use session feature to call the variable instead of including a page, because it will indeed load an entire page. Please be more specific about your goal, perhaps we can help more by knowing more.
The whole HTML content of formvalidation.php will come up on the screen (so everything outside of <?php ?> just like all the outputs (echo etc ...) of the included file will come up on the screen.
You can avoid that by removing the outputs and only putting functions and variable declarations into the included file formvalidation.php.
The content of formvalidation.php could eg. be:
<?php
$name = 'test';
?>
It's going to execute whatever's in formvalidation.php. All the include function does is basically replace that line with the contents of your included file.
So if you don't want to show what's in that file - enclose the entire file in a function, or multiple functions. This is the way your library files (that you include) should be. Nothing in that file should be outside of a function definition.
Example (it's a crappy programming practice, but for example) -
formvalidation.php was ->
<?php
echo "hola";
if ($i = 5) {
echo 15;
}
?>
<form><input type="text" value= "10"/>
<?php
echo "macho, macho man.";
?>
Everything gets shown when I include it.
formvalidation.php now ->
<?php
function validate_form() {
echo "hola";
if ($i = 5) {
echo 15;
}
?>
<form><input type="text" value= "10"/>
<?php
echo "macho, macho man.";
}
?>
Now the way I've changed the file - nothing will get printed until I call validate_form();
Does that make sense?
When you use include 'someFile.php'; it's like you are taking all the contents of that file and pasting it in the code. For example if I had:
someFile.php
echo '<h1>Hello World</h1>';
echo '<p>I like pie</p>';
then:
include 'someFile.php';
echo $name;
Is the same as:
echo '<h1>Hello World</h1>';
echo '<p>I like pie</p>';
echo $name;
As others have said, that's what include does. I assume that you define $name inside the formvalidation.php file and that is why you are including it.
The right solution here would be to seperate the code in formvalidation.php into a function/class/file which does the data processing and another which creates the output. The you include/call only the first in the situation where you don't want the output
However, it is possible to capture the output and then discard it, using output buffering:
<?php
ob_start(); //Start capturing output
include 'formvalidation.php';
ob_end_clean(); // Stop capturing output and discard whatever was captured
echo $name;
?>
That said I would really not recommend this. The recommended way to fix this is to seperate your back-end code from your output generating code and only call what you actually need in any given situation.
Edit
An example of how to seperate the issues properly could be the following.
Lets assume your current formvalidation.php is something like:
<?php
$name = $_REQUEST['name'];
if( '' == $name ){ ?>
<p class="error">You must supply a name</p>
<form action="foo.php">
<input name="name" />
<button type="submit">Submit</button>
</form><?php
} else {
echo '<p>Form valid!</p>';
}
In a new file validator.php you could do:
<?php
class MyValidator{
public $name;
function read_data(){
$this->name = $_REQUEST['name'];
}
function validate(){
if( '' == $name ){ ?>
<p class="error">You must supply a name</p>
<form action="foo.php">
<input name="name" />
<button type="submit">Submit</button>
</form><?php
} else {
echo '<p>Form valid!</p>';
}
}
}
Then you change you formvalidtion.php to
<?php
require_once 'validator.php';
$val = new MyValidator();
$val->read_data();
$val->validate();
While the file you have above becomes
<?php
require_once 'validator.php';
$val = new MyValidator();
$val->read_data();
echo $val->name;

Admin Panel: PHP form doesn't send data to MySQL

I have a simple code to add banners from admin panel to the index of the site. But the add function doesnt work correctly here is the form to add banner
<h2>Add Banner</h2>
<?php include ("../engine/config/config.php"); ?>
<form method="post" action="">
Clicks
<input type="text" name="click" value="0" style="width: 200px;" /> <div class="hr"></div>
Impressions
<input type="text" name="imp" value="0" style="width: 200px;" /> <div class="hr"></div>
LINK
<input type="text" name="url" value="http://" style="width: 200px;" /> <div class="hr"></div>
Size
<select name="razmer">
<option value='468x60'>468x60</option>
<option value='88x31'>88x31</option>
</select>
<div class="hr"></div>
Banner<br />
<input type="text" name="picurl" value="http://" style="width: 200px;" /><div class="hr"></div>
<input type="submit" name="submit" value="Submit"> <br />
</form>
<?
if($_POST['submit']) {
$click = $_POST['click'];
$imp = $_POST['imp'];
$url = $_POST['url'];
$razmer = $_POST['razmer'];
$picurl = $_POST['picurl'];
$sql = "INSERT INTO `banneradd` (click, imp, url, razmer, picurl, username) VALUES ('$click', '$imp', '$url', '$razmer', '$picurl', '')";
$result = mysql_query($sql);
echo "<div class='hr'>The Banner has been added, please go back to the index: <a href='view_reklama.php'> Index </a></div>";
}
?>
So it say it was added but when I go back ITS NOT. There is no error or anything, can someone help? Thanks in advance :)
Okay, there are way too many things wrong with your code, so if you're learning from a particular site or person... find a different source.
Don't open PHP with <?. This is the shorthand style. It is disabled on many if not most web servers, and for good reason -- because XML introduces its encoding using the same opening <? and it causes conflict. Always open your PHP with <?php. http://www.php.net/manual/en/ini.core.php#ini.short-open-tag
Don't use if($_POST['submit']), use if (isset($_POST['submit'])). Your current script should generate an error, but it's probably being masked because PHP defaults to not showing very many errors. It does trigger a warning, though, because you're checking if the variable (or rather array value) $_POST['submit'] is equal to true. In fact, that variable is undefined. Use isset() to check if a variable exists. http://php.net/manual/en/function.isset.php
Sanitize your user's input. If somebody typed a ' into any of your fields, your query would break. Why? Because in your query, you're placing your stringed values in single quotes, and any instance of another single quotation mark would break out of that. There is such a thing as magic quotes in PHP (which automatically escapes POST values), but it's absolutely awful, so please disable it. http://php.net/manual/en/security.magicquotes.php The best way to escape user input is with real escape functions (more on that later).
mysql_ functions are deprecated. Use PDO or MySQLi. If you're getting used to the mysql_ functions, it is easier to transition to MySQLi. For simplicity, I'll use the procedural style, but it's much better to go with the OOP style....
If you want to debug MySQL commands with PHP, you should format your queries carefully, print the error, and also print the computed query, because sometimes you need to look at the actual resulted query in order to see what is wrong with it.
That said, here's what I suggest:
<?php
error_reporting(E_ALL);
// Turn on all error reporting. Honestly, do this every time you write a script,
// or, better yet, change the PHP configuration.
$connection = mysqli_connect('host', 'username', 'password', 'database');
// Somewhere in your config file, I assume you're calling mysql_connect.
// This is a pretty similar syntax, although you won't need mysql_select_db.
if (isset($_POST['submit'])) {
$click = mysqli_real_escape_string($connection, $_POST['click']);
// This will escape the contents of $_POST['click'], e.g.
// if the user inputted: Hello, 'world'! then this will produce:
// Hello, \'world\'!
$imp = mysqli_real_escape_string($connection, $_POST['imp']);
$url = mysqli_real_escape_string($connection, $_POST['url']);
$razmer = mysqli_real_escape_string($connection, $_POST['razmer']);
$picurl = mysqli_real_escape_string($connection, $_POST['picurl']);
$query = "
INSERT INTO `banneradd` (
`click`,
`imp`,
`url`,
`razmer`,
`picurl`,
`username`
)
VALUES
(
'$click',
'$imp',
'$url',
'$razmer',
'$picurl',
''
);
";
// Format your query nicely on multiple lines. MySQL will tell you what line
// the error occurred on, but it's not helpful if everything's on the same line.
$result = mysqli_query($connection, $query);
$error = mysqli_error($connection);
if ($error) {
echo "A MySQL error occurred: $error<br>";
echo "<pre>$query</pre>";
// If an error occurred, print the error and the original query
// so you can have a good look at it.
die;
// Stop executing the PHP.
}
echo '<div class="hr">The Banner has been added, please go back to the index: Index </div>';
}
?>
See if that helps. Chances are, the MySQL error will be helpful with diagnosing the problem. You might have just misspelled a column name or table name.

file_get_contents displays nothing when used with $_GET

I'm having a problem when using file_get_contents combined with $_GET. For example, I'm trying to load the following page using file_get_contents:
https://bing.com/?q=how+to+tie+a+tie
If I were to load it like this, the page loads fine:
http://localhost/load1.php
<?
echo file_get_contents("https://bing.com/?q=how+to+tie+a+tie");
?>
However, when I load it like this, I'm having problems:
http://localhost/load2.php?url=https://bing.com/?q=how+to+tie+a+tie
<?
$enteredurl = $_GET["url"];
$page = file_get_contents($enteredurl);
echo $page;
?>
When I load using the second method, I get a blank page. Checking the page source returns nothing. When I echo $enteredurl I get "https://bing.com/?q=how to tie a tie". It seems that the "+" signs are gone.
Furthermore, loading http://localhost/load2.php?url=https://bing.com/?q=how works fine. The webpage shows up.
Anyone know what could be causing the problem?
Thanks!
UPDATE
Trying to use urlencode() to achieve this. I have a standard form with input and submit fields:
<form name="search" action="load2.php" method="post">
<input type="text" name="search" />
<input type="submit" value="Go!" />
</form>
Then to update load2.php URL:
<?
$enteredurl = $_GET["url"];
$search = urlencode($_POST["search"]);
if(!empty($search)) {
echo '<script type="text/javascript">window.location="load2.php?url=https://bing.com/?q='.$search.'";</script>';
}
?>
Somewhere here the code is broken. $enteredurl still returns the same value as before. (https://bing.com/?q=how to tie a tie)
You have to encode your parameters properly http://localhost/load2.php?url=https://bing.com/?q=how+to+tie+a+tie should be http://localhost/load2.php?urlhttps%3A%2F%2Fbing.com%2F%3Fq%3Dhow%2Bto%2Btie%2Ba%2Btie. you can use encodeURIComponent in JavaScript to do this or urlencode in php.
<?
$enteredurl = $_GET["url"];
$search = urlencode($_POST["search"]);
if(!empty($search)) {
$url = urlencode('https://bing.com/?q='.$search)
echo '<script type="text/javascript">window.location="load2.php?url='.$url.'";</script>';
}
?>

Calling Javascript function from PHP function

Below is my code in a single PHP file named testOne.php
<html>
<head>
<script type="text/javascript">
function testAlert(firstValue, secondValue)
{
alert ("Passed: "+firstValue+secondValue);
}
</script>
</head>
<body>
....
</body>
</html>
<?php
function testPassedValues($One, $Two)
{
echo "<input type = \"button\" onclick = \"testAlert($One[2], $Two[2])\">Click Here!</input>";
}
$link = mysql_connect("localhost", "root", "");
if (mysql_select_db("myDatabase", $link))
{
$result = mysql_query("SELECT * FROM MYTABLE");
while($currRowOne = mysql_fetch_row($result) &&
$currRowTwo = mysql_fetch_row($result))
{
testPassedValues($currRowOne, $currRowTwo);
}
}
?>
To help in understanding, I am calling a javascript method testAlert() from the PHP function testPassedValues(). However, I am not sure what the issue is since the call is not successful. In Mozilla(Firebug), I don't find any issues and in Chrome->Developer Tools, I get the error Uncaught Syntaxerror: Unexpected token ILLEGAL in the console.
Can anyone please help me as to the root cause here?
I don't think you've fully understood where and how JavaScript and PHP are executed.
PHP is run on the server. It generates an HTML page (potentially containing JavaScript), which is then sent to the client. The PHP is now finished.
The client's web browser then runs the JavaScript.
To debug your JavaScript problem, take a look at the web page the client actually saw. If Firebug is reporting a problem, that's where it is.
Most likely the values of $One[2] and $Two[2] are strings, so the generated HTML is:
<input type = "button" onclick = "testAlert(string one, string two)">Click Here!</input>
Which is obviously invalid javascript.
Enclose the parameters in quotes:
echo "<input type = \"button\" onclick = \"testAlert('$One[2]', '$Two[2]')\">Click Here!</input>";
You should also correctly escape the of $One[2] and $Two[2] values for HTML and JavaScript, so that you don't introduce XSS flaws or errors when a string contains an apostraphe. I'll leave that up to you to figure out.

PHP setcookie warning

I have a problem with 'setcookie' in PHP and I can't solve it.
so I receive this error "Warning: Cannot modify header information - headers already sent by (output started at C:\Program Files\VertrigoServ\www\vote.php:14) in C:\Program Files\VertrigoServ\www\vote.php on line 86"
and here is the file..
line 86 is setcookie ($cookie_name, 1, time()+86400, '/', '', 0);
is there any other way to do this ??
<html>
<head>
<title>Ranking</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#EEF0FF">
<div align="center">
<br/>
<div align="center"><div id="header"></div></div>
<br/>
<table width="800" border="0" align="center" cellpadding="5" cellspacing="0" class="mid-table">
<tr><td height="5">
<center>
</tr>
</table>
</center>
</td></tr>
<tr><td height="5"></td></tr>
</table>
<br/>
<?php
include "conf.php";
$id = $_GET['id'];
if (!isset($_POST['submitted']))
{
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
</div></td></tr>
<tr><td align="center" valign="top"><img src="images/ads/top_banner.png"></td></tr>
</table>
</form>
<?php
}
else
{
echo '<font color="red">You must select a valid server to vote for it!</font>';
}
}
else
{
$kod=$_POST['kod'];
if($kod!=$_COOKIE[imgcodepage])
{
echo "The code does not match";
}
else
{
$id = mysql_real_escape_string($_POST['id']);
$query = "SELECT SQL_CACHE id, votes FROM s_servers WHERE id = $id";
$result = mysql_query($query) OR die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$votes = $row['votes'];
$id = $row['id'];
$cookie_name = 'vote_'.$id;
$ip = $_SERVER['REMOTE_ADDR'];
$ltime = mysql_fetch_assoc(mysql_query("SELECT SQL_CACHE `time` FROM `s_votes` WHERE `sid`='$id' AND `ip`='$ip'"));
$ltime = $ltime['time'] + 86400;
$time = time();
if (isset($_COOKIE['vote_'.$id]) OR $ltime > $time)
{
echo 'You have already voted in last 24 hours! Your vote is not recorded.';
}
else
{
$votes++;
$query = "UPDATE s_servers SET votes = $votes WHERE id = $id";
$time = time();
$query2 = mysql_query("INSERT INTO `s_votes` (`ip`, `time`, `sid`) VALUES ('$ip', '$time', '$id')");
$result = mysql_query($query) OR die(mysql_error());
setcookie ($cookie_name, 1, time()+86400, '/', '', 0);
}
}
}
?>
<p>[Click here if you don't want to vote]</p><br/>
<p>Ranking.net © 2010-2011<br> </p>
</div>
</body>
</html>
Thanks a lot!
You cannot have any output before header() and setcookie() calls.
https://stackoverflow.com/search?q=+headers+already+sent+by
https://stackoverflow.com/tags/php/info
Any output includes any <html> before the openeing <?php marker, or any print or echoing of content. Another culprit is the UTF-8 BOM http://en.wikipedia.org/wiki/Byte_Order_Mark - which most text editors do not show visibly, but confuses PHP when at the beginning of files.
Setting a cookie requires sending a header to the client, and you can't send headers if the output has already started.
You have to put the PHP code before the HTML markup so that you can call setcookie before any output is sent and you also separate PHP code from presentation which you should do anyway.
You should put the cookie code at the top of the page. A better layout would be something like this:
<?php
//include config
//check posted data (included settings cookies)
//set needed variables
?>
<html>
.....
You could also separated the php code and html. This is generally what i do. My uses generally involve a view class or (in the past) smarty. but a quick example would be to add this code at the bottom of the above php code and get rid of the html:
<?php
if(empty($tpl)) {
$tpl = 'index';
}
if(file_exists("template/{$tpl}.tpl.php")) {
include("template/{$tpl}.tpl.php");
}
else {
header('Location: /');
}
?>
YOu would need to create a directory called 'templates' and add the html code to files that end in the .tpl.php extension.
Really they are just php pages, but the .tpl. part help you remember that its just mark up.
Make them php pages (not html) so you can output variables
Then in your varios parts of your code above you would set $tpl to be the template you want to load.
This is a just a base bit of code, but it should give you a general idea on how to separate this data. THe main idea is that all html and text will be outputted "after" all programming code has been done.
What you need to do is to create a nice buffer to hold all the headers in until you are down processing. ob_start does the job for you and here is a reference to it. http://php.net/manual/en/function.ob-start.php
When you are finished loading all the different headers use ob_get_contents like this
$text = ob_get_contents();
echo($text);
ob_end_clean();
I hope this helps.
You can not use PHP to set a cookie after any thing has been outputted, and the html before the first php tag does count as output. to keep to a purely php method you'd have to move the whole part about determining what to put int he cookie and setting it up to the very top.
or what I do in situations where that would require to much extra work to do it that way is to have php echo out the JavaScript code to set a cookie. now if you make or get a nice JS cookie setting function and either embed it or link it into the page. then all you have to do is have php echo the function call with the proper data in it at that point. then when the page loads while php still will not set the cookie, but when the browser when it runs the js code it will. and so you get what you want the cookie is set. and you did not have to move the stuff up to the top.

Categories