How can I use a php file's output with Ajax? - php

I was following this tutorial.
I need to use a php file's ouput in my HTML file to dynamically load images into a gallery. I call
function setOutput()
{
if (httpObject.readyState == 4)
document.getElementById('main').src = httpObject.responseText;
alert("set output: " + httpObject.responseText);
}
from
function doWork()
{
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "gallery.php?no=0", true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
However, the alert returns the php file, word for word. It's probably a really stupid error, but I can't seem to find it.
The php file:
<?php
if (isset($_GET['no'])) {
$no = $_GET['no'];
if ($no <= 10 && $no >1) {
$xml = simplexml_load_file('gallery.xml');
echo "images/" . $xml->image[$no]->src;
}
else die("Number isn't between 1 and 10");
}
else die("No number set.");
?>

If the alert is returning the contents of the PHP file instead of the results of executing it, then the server is not executing it.
Test by accessing the URI directly (instead of going via JavaScript).
You probably need to configure PHP support on the server.

Your Server doesn't serve/parse PHP files! You could test your JavaScript code by setting the content of gallery.php to the HTML code you want to receive.

Related

How to add an error handling to read an XML file in php?

I am developing a PHP script that allows me to modify tags in an XML file and move them once done.
My script works correctly but I would like to add error handling: So that if the result of my SQL query does not return anything display an error message or better, send a mail, and not move the file with the error and move to the next.
I did some tests but the code never displays the error and it moves the file anyway.
Can someone help me to understand why? Thanks
<?php
}
}
$xml->formatOutput = true;
$xml->save($source_file);
rename($source_file,$destination_file);
}
}
closedir($dir);
?>
Give this one a try
$result = odbc_fetch_array($exec);
if ($result === false || $result['GEAN'] === null) {
echo "GEAN not found for $SKU_CODE";
// continue;
}
$barcode = (string) $result['GEAN'];
echo $barcode; echo "<br>"; //9353970875729
$node->getElementsByTagName("SKU")->item(0)->nodeValue = "";
$node->getElementsByTagName("SKU")->item(0)->appendChild($xml->createTextNode($result[GEAN]));

php: shellscript running before screen-output

I'm currently putting together a small web-based GUI to generate kickstart-scripts. I got a confirmation page that's sending the relevant data via POST to the PHP-page where the actual shell script is called to build the iso. So far it's working, but the page seems to execute the script before it outputs anything else (for example, the 'echo' I put in at the beginning of the page ...), and I'm absolutely clueless why. Would anyone care to enlighten me?
Here's the code to the PHP-page that's executing the shell script ...
echo 'Generating your ISO; this might take a while...';
sleep(20);
if (!isset($_POST['auth'])) {
$ad = 'N';
}
else {
$ad = 'Y';
}
if (!isset($_POST['oracle'])) {
$oracle = 'N';
}
else {
$oracle = 'Y';
}
if ((!isset($_POST['ip'])) or (!isset($_POST['hostname'])) or (!isset($_POST['rhsel'])) or (!isset($_POST['submit'])) or (!isset($_POST['gw'])) or (!isset($_POST['nm']))) {
die('Please use the correct form !');
}
if (isset($_POST['ip'])) {
$ip = trim($_POST['ip']);
}
if (isset($_POST['gw'])) {
$gw = trim($_POST['gw']);
}
if (isset($_POST['nm'])) {
$nm = trim($_POST['nm']);
}
if (isset($_POST['hostname'])) {
$hostname = trim($_POST['hostname']);
}
if (isset($_POST['rhsel'])) {
$rhsel = $_POST['rhsel'];
}
passthru("/usr/bin/sudo /data/skripte/webconfig.sh $rhsel $oracle $ad $ip $gw $nm $hostname 2>&1");
PHP scripts accessed via a browser are request-response, meaning all processing is done on the server prior to headers and content being sent to the client. This means you will not get a continually updating output like you would see on the command line. There is no way around this. Sorry.

PHP: Running PHP scripts without going on webpage?

I use WAMP and ever since I have learned PHP, I have been running my php scripts by going on the webpage itself to see the output. For example, to see the output on a script called script.php, I go on localhost/script.php.
Is there a better way to do this? I mean, in Java there's Eclipse and you can just click the green button and it'll run the code for you and see immediate output. Is there something like this for PHP?
It is possible to run PHP scripts from the command line without a web server. To do this add the following logic to your script:
if (defined('STDIN')) {
if (isset($argv)){
// handle your command line arguments here with getopt
}
}
// GET request parameter definitions //
else {
// handle your URL parameters (via GET or POST requests) here
}
When the script is run from the command line with the PHP interpreter
php myfile.php -s --longflag <argument>
STDIN is defined and you can handle command line switches, flags, and arguments with getopt in the if block.
The script reaches the else block when you access it by URL on a web server. The PHP code that you currently have can be placed in that block.
Here's an example from one of my projects that demonstrates how to handle the URL parameters as short or long command line options:
// Command line parameter definitions //
if (defined('STDIN')) {
// check whether arguments were passed, if not there is no need to attempt to check the array
if (isset($argv)){
$shortopts = "c:";
$longopts = array(
"xrt",
"xrp",
"user:",
);
$params = getopt($shortopts, $longopts);
if (isset($params['c'])){
if ($params['c'] > 0 && $params['c'] <= 200)
$count = $params['c']; //assign to the count variable
}
if (isset($params['xrt'])){
$include_retweets = false;
}
if (isset($params['xrp'])){
$exclude_replies = true;
}
if (isset($params['user'])){
$screen_name = $params['user'];
}
}
}
// Web server URL parameter definitions //
else {
// c = tweet count ( possible range 1 - 200 tweets, else default = 25)
if (isset($_GET["c"])){
if ($_GET["c"] > 0 && $_GET["c"] <= 200){
$count = $_GET["c"];
}
}
// xrt = exclude retweets from the timeline ( possible values: 1=true, else false)
if (isset($_GET["xrt"])){
if ($_GET["xrt"] == 1){
$include_retweets = false;
}
}
// xrp = exclude replies from the timeline (possible values: 1=true, else false)
if (isset($_GET["xrp"])){
if ($_GET["xrp"] == 1){
$exclude_replies = true;
}
}
// user = Twitter screen name for the user timeline that the user is requesting (default = their own, possible values = any other Twitter user name)
if (isset($_GET["user"])){
$screen_name = $_GET["user"];
}
} // end else block
I find this to be helpful for testing. Hope it helps.
Jetbrains PHP storm is a good debugging tool
If you use Sublime Text as text editor you can use XDebug

PHP to ASP.NET conversion

Does anyone know how to convert the following PHP code to ASP.NET?
<?php
$myFile = "includes/status.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 1);
$status= $theData;
if ( $status == 0) {
include('includes/bol_down.php');
}
elseif ($status == 1){
include('includes/login_form_up.php');
}
fclose($fh);
?>
Probably depends a lot on what's being included. ASP.NET doesn't "include" other code in this manner.
If the code being included is just PHP code, then there's no need for this in ASP.NET. The compiled assembly has all of the available code from the compilation already available.
If the code being included is actual page output, then it's a different model for how you'd accomplish this. The closest analogy would be to conditionally display a user control. Something like this:
if (status == 0)
{
var myControl = (MyControlType)LoadControl("~/MyControl.ascx");
myPlaceHolder.Controls.Add(myControl);
}
else if (status == 1)
{
var myOtherControl = (MyOtherControlType)LoadControl("~/MyOtherControl.ascx");
myPlaceHolder.Controls.Add(myOtherControl);
}
In this case, myPlaceHolder is an existing control on the page which exists solely as a, well, placeholder in order to add controls dynamically. This is because the page life cycle is different in ASP.NET than in PHP. In PHP the scripts are added in-line, whereas in ASP.NET the user controls are inserted into existing markup structure.
int status = theData;
if(status == 0)
{
Response.WriteFile("includes/bol_down.html");
}
else if(status == 1)
{
Response.WriteFile("includes/login_form_up.html");
}
I'm assuming theData is of type int (integer).
Couple things to note. ASP.NET precompiles before deployment which is why you can't dynamically add using include. Instead, you have to write the file directly to the output stream (WriteFile()). Also, the file you include can't contain ASP.NET server side code. If it does, the code won't be executed, it will simply be displayed to the user. There may be an alternative to what you're trying to achieve. You can read more on dynamically including the file here.
<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
include_once "ez_sql_core.php";
include_once "ez_sql_mysql.php";
$db = new ezSQL_mysql('db_user','db_password','db_name','db_host');
$song = $db->get_row("SELECT * FROM songs ORDER BY RAND() LIMIT 1");
$artist = $song->artist;
$songname = $song->title;
$url = $song->url;
$separator = '|';
echo $url.$separator.$artist.$separator.$songname;
}
?>

PHP variable from external .php file, inside JavaScript?

I have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.

Categories