I'm very new to PHP, and I can't figure out why this is happening.
For some reason, when exit fires the entire page stops loading, not just the PHP script. Like, it'll load the top half of the page, but nothing below where the script is included.
Here's my code:
$page = $_GET["p"] . ".htm";
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
exit;
}
if ($_POST["page"]) {
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_POST["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
exit;
}
if (file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
exit;
}
Even if you have HTML code following your PHP code, from the web server's perspective it is strictly a PHP script. When exit() is called, that is the end of it. PHP will output process and output no more HTML, and the web server will not output anymore html. In other words, it is working exactly as it is supposed to work.
If you need to terminate the flow of PHP code execution without preventing any further HTML from being output, you will need to reorganize your code accordingly.
Here is one suggestion. If there is a problem, set a variable indicating so. In subsequent if() blocks, check to see if previous problems were encountered.
$problem_encountered = FALSE;
if (!$_GET["p"]) {
echo("<h1>Please click on a page on the left to begin</h1>\n");
// problem here
// Set a boolean variable indicating something went wrong
$problem_encountered = TRUE;
}
// In subsequent blocks, check that you haven't had problems so far
// Adding preg_match() here to validate that the input is only letters & numbers
// to protect against directory traversal.
// Never pass user input into file operations, even checking file_exists()
// without also whitelisting the input.
if (!$problem_encountered && $_GET["page"] && preg_match('/^[a-z0-9]+$/', $_GET["page"])) {
$page = $_GET["p"] . ".htm";
$handle = fopen("../includes/$page", "w");
fwrite($handle, $_GET["page"]);
fclose($handle);
echo("<p>Page successfully saved.</p>\n");
// problem here
$problem_encountered = TRUE;
}
if (!$problem_encountered && file_exists("../includes/$page")) {
$FILE = fopen("../includes/$page", "rt");
while (!feof($FILE)) {
$text .= fgets($FILE);
}
fclose($FILE);
} else {
echo("<h1>Page "$page" does not exist.</h1>\n");
// echo("<h1>New Page: $page</h1>\n");
// $text = "<p></p>";
// problem here
$problem_encountered = TRUE;
}
There are lots of ways to handle this, many of which are better than the example I provided. But this is a very easy way for you to adapt your existing code without needing to do too much reorganization or risk breaking much.
In PHP 5.3+ you can use the goto statement to jump to a label just before the ?> instead of using exit in the example given in the question.
It would'n work well with more structured code (jumping out of functions), tough.
Maybe this should be a comment, who knows.
Related
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]));
I have some code to get some public available data that i am fetching from a website
//Array of params
foreach($params as $par){
$html = file_get_html('WEBSITE.COM/$par');
$name = $html->find('div[class=name]');
$link = $html->find('div[class=secondName]');
foreach($link as $i => $result2)
{
$var = $name[$i]->plaintext;
echo $result2->href,"<br>";
//Insert to database
}
}
So it goes to the given website with a different parameter in the URL each time on the loop, i keep getting errors that breaks the script when a 404 comes up or a server temporarily unavailable. I have tried code to check the headers and check if the $html is an object first but i still get the errors, is there a way i can just skip the errors and leave them out and carry on with the script?
Code i have tried to checked headers
function url_exists($url){
if ((strpos($url, "http")) === false) $url = "http://" . $url;
$headers = #get_headers($url);
//print_r($headers);
if (is_array($headers)){
//Check for http error here....should add checks for other errors too...
if(strpos($headers[0], '404 Not Found'))
return false;
else
return true;
}
else
return false;
}
Code i have tried to check if object
if (method_exists($html,"find")) {
// then check if the html element exists to avoid trying to parse non-html
if ($html->find('html')) {
// and only then start searching (and manipulating) the dom
You need to be more specific, what kind of errors are you getting? Which line errors out?
Edit: Since you did specify the errors you're getting, here's what to do:
I've noticed you're using SINGLE quotes with a string that contains variables. This won't work, use double quotes instead, i.e.:
$html = file_get_html("WEBSITE.COM/$par");
Perhaps this is the issue?
Also, you could use file_get_contents()
if (file_get_contents("WEBSITE.COM/$par") !== false) {
...
}
How do I make the die() message to echo in a certain place in the HTML section of the same page?
$files = array();
$upload = $_FILES['upload']['tmp_name'];
foreach($upload as $uploaded){
if(!empty($uploaded)) {
if(isset($uploaded)){
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime= finfo_file($finfo, $uploaded);
switch($mime) {
case 'application/pdf':
break;
default:
die('pdf file only.');
break;
}
}
}
}
die will immediately stop execution and send anything in buffers to the browser.
Personally, I like to do something like this:
function halt($str="") {
if( $str) echo "<div class=\"server_notice\">".$str."</div>";
require("template/foot.php");
exit;
}
How about don't just use die, do something to insert html there and then die.
Alternatively, you have register_shutdown_function (Documentation: http://php.net/manual/es/function.register-shutdown-function.php) which will allow you to do things right after the script is ended with die;
There is no way to do that. die() or exit() will stop executing of your script.
Thouh, you can make some error reporting system.
$lastError = null
Then do what you want and set this error.
Then you can check it in some place:
if ($lastError == 2){
echo "The file is no in PDF format" ;
} //and so on.
Also you could create some constants like:
define("ERROR_WRONG_FORMAT", 2); //Make the error clear.
You'll need to echo out div tags and then position them using CSS.
die('<div id="error">pdf file only.</div>');
Then add the following text to your CSS:
#error{position:absolute;top:10;left:10;}
You'll need to change the top and left values depending on where you wnat them to be.
If you don't know what CSS is, I suggest you watch TheNewBoston's tutorials on YouTube!
So I have a simple form that takes a user input, passes it to a separate PHP script that does some processing on a different domain, and posts a txt file if successful. Example:
<form method="GET" action="inventory_check.php" target="_blank">
Part Number <input type="text" name="part" /><input type="submit" value="Check Inventory" />
</form>
<?php
$filename = $userInput;
if (file_exists('ftpMain/'.$filename.'')) {
$handle = fopen("ftpMain/".$filename."", "r");
$output = fread($handle, filesize('ftpMain/'.$filename.''));
fclose($handle);
$output = trim($output, '&l0O(10U');
$output = trim($output, 'E ');
echo $output;
}
else {
echo 'Failure.';
}
?>
So, inventory_check.php obviously is an inventory lookup for us, however, it's contained on another server (different domain) so it completes its processing and posts it to a file, that I read, cleanup, and display. Now my issue is twofold, I need to grab and keep the input from the user to find the filename and the second is I need to page to either reload or recheck if the file exists. What is the best approach to do this?
Note: We use an awful in house DBMS, so posting and retrieving from a DB is not an option, it took us a while to get it to read the input and FTP it correctly, so it looks like this is the only path.
Why don't you make the request in your server A? by using curl, so you could get the response right after the query.
Firstly, you'll need to get the user's input properly, and sanitize it. I'll leave out the details of the sanitize() method, as that's not really what you're asking.
<?php
if(isset($_POST)) {
$part_number = sanitize($_POST['part']);
$filename = "ftpMain/$part_number";
if (file_exists($filename)) {
$handle = fopen($filename, "r");
$output = fread($handle, filesize($filename));
fclose($handle);
/* Do things with output */
} else {
echo 'Failure.';
}
}
?>
However, you say that the file is on another server - looking for ftpMain/... is only going to look for a directory called ftpMain in your current directory. Is the file publicly available on the internet? If it is, you could do something like this:
<?php
$url = "http://yourserver.com/parts/$part_number.txt";
$response = get_headers($url, 1);
if ($response[0] == 'HTTP/1.1 200 OK') {
/* The file exists */
} else {
/* The file does not exist */
}
?>
I hope I've understood your question correctly - this assumes that the form action is pointing to itself. That is, your file with this code is also called inventory_check.php.
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;
}
?>