Php foreach echo (if/else) [duplicate] - php

This question already has answers here:
Turn off warnings and errors on PHP and MySQL
(6 answers)
Closed 5 years ago.
It prints on the screen when it is correctly entered, but I do not want to do anything when it is entered incorrectly
How can I do that?
<?php
header('Content-type: text/html; charset=utf8');
$api_key = 'local';
$keyword = 'test';
$url = 'test.json' . $api_key . '&' .'keyword' .'=' . $GLOBALS['q'] ;
$open = file_get_contents($url);
$data = json_decode($open, true);
$istatistikler = $data['data'];
if ($data) {
foreach ( $istatistikler as $istatistik ){
echo '<div class="right">';
echo 'Oyun modu: ' . $istatistik['title'] . '<br />' .
'Kazanma: ' . $istatistik['content'] . '<br />' .
'Kazanma: ' . $istatistik['image'] . '<br />' .
'Kazanma: ' . $istatistik['category'] . '<br />' .
'<br />' .
'<hr/>';
$karakter_simge = 'http://google.com' . $istatistik['image'] . '';
echo "<img src=".$karakter_simge." >" ;
echo '</div>';
}
}
?>
Successful output
Failed output
Warning:
file_get_contents(http://localhost/api/detail?X-Api-Key=local&keyword=a):
failed to open stream: HTTP request failed! HTTP/1.1 406 Not
Acceptable in /opt/lampp/htdocs/weather-master/php/php-api.php on line
10
"I do not want to print unsuccessfully"
thank you for your help!

This may be helpful:
$open = #file_get_contents($url);
# sign before a function name (in a call) prevents from showing any warnings (It's a bad practice though).
Good luck!

Change
$open = file_get_contents($url);
into
$open = #file_get_contents($url);
if ($open === false)
die("wrong");
The # suppresses the error message. Using die() will abort the script completely with the given message.
Alternatively, change the condition to !== false and wrap the rest of your "successful" code in its body:
$open = #file_get_contents($url);
if ($open !== false)
{
$data = json_decode...
...
...
}
I guess I overshot the goal here a little, but not even running into code that won't work properly without its data isn't a bad idea at all.

Related

I am not getting Output for this PHP Program

I am not getting Output though i include all the files
<?php
/**
* Scan network to retrieve hosts and services information.
*/
require_once 'C:/xampp/php/pear/Net/Nmap.php';
//Define the target to scan
$target = array('127.0.0.1','localhost');
$options = array('nmap_binary' => 'C:/Program Files (x86)/Nmap');
try {
$nmap = new Net_Nmap($options);
//Enable nmap options
$nmap_options = array('os_detection' => true,
'service_info' => true,
'port_ranges' => 'U:53,111,137,T:21-25,80,139,8080',//to scan only specified ports
);
$nmap->enableOptions($nmap_options);
//Scan target
$res = $nmap->scan($target);
//Get failed hosts
$failed_to_resolve = $nmap->getFailedToResolveHosts();
if (count($failed_to_resolve) > 0) {
echo 'Failed to resolve given hostname/IP: ' .
implode (', ', $failed_to_resolve) .
"\n";
}
//Parse XML Output to retrieve Hosts Object
$hosts = $nmap->parseXMLOutput();
//Print results
foreach ($hosts as $key => $host) {
echo 'Hostname: ' . $host->getHostname() . "\n";
echo 'Address: ' . $host->getAddress() . "\n";
echo 'OS: ' . $host->getOS() . "\n";
echo 'Status: ' . $host->getStatus . "\n";
$services = $host->getServices();
echo 'Number of discovered services: ' . count($services) . "\n";
foreach ($services as $key => $service) {
echo "\n";
echo 'Service Name: ' . $service->name . "\n";
echo 'Port: ' . $service->port . "\n";
echo 'Protocol: ' . $service->protocol . "\n";
echo 'Product information: ' . $service->product . "\n";
echo 'Product version: ' . $service->version . "\n";
echo 'Product additional info: ' . $service->extrainfo . "\n";
}
}
} catch (Net_Nmap_Exception $ne) {
echo $ne->getMessage();
}
?>
if your program do not have any output, it means you have syntax error, fatal error or segment error.
change php.ini setting, enable, dispaly_errors, and error_reporting with E_ALL
usually, this is enough. you can see the error message and fix the bug.
if there still not error message, try create a simple file, only show phpinfo().
if this is ok, usually, you do not have start up error, if not, enable display_startup_errors in php.ini
if you still have no error, check your apache or nginx configure, you probably config the site wrong.
if you still have no error, congratulation! you got segment error.
use gdb to find the reason.

Determining if a file DOES NOT exist

I have some code which seems logical but is not working as expected.
<?php
$ukip_code = "PTXC";
$show_logo = "http://www.ukipme.com/img/confs/" . strtolower($ukip_code) . ".gif";
echo $show_logo . "<br>";
echo "<img src=" . $show_logo . "><br>";
if (!file_exists($show_logo)) { // or file_exists($show_logo) === false
$show_logo = "http://placehold.it/165x100/&text={$ukip_code}";
}
echo $show_logo;
?>
My first echo shows the original file's URL. I then echo an img tag to prove that this file is an actual file.
I then check if the file exists, and if it does not, use a placeholder image. Echoing this variable now should give the original URL again (as it quite clearly does exist), but it gives the placeholder URL. Why?
I've also tried using file_exists($show_logo) === false in my if statement, but I get the same result.
You can use get_headers() method to get the status of the resource:
http://php.net/manual/en/function.get-headers.php
$regex = "(200|201|203|204|205|206)";
$headers = get_headers($show_logo);
preg_match($regex, $headers[0], $match);
if (!$match) {
$show_logo = "http://placehold.it/165x100/&text={$ukip_code}";
}
echo $show_logo;
You should use the server path to the site, not the url of the site. Something like /home/etc/file_name
Your var should be like this
$show_logo = "/{the site server path}/img/confs/" . strtolower($ukip_code) . ".gif";
if you need __FILE__ constant will give you absolute path to current file.
You can try to read in the contents which is behind the url. The drawback however is that this will generate some traffic for big images. But it makes sure that if the file can be downloaded from the given url that it is available. There is curl_setopt which could give you some more options.
<?php
$ukip_code = "PTXC";
$opt = FALSE;
$show_logo = "http://www.ukipme.com/img/confs/" . strtolower($ukip_code) . ".gif";
echo $show_logo . "<br>";
echo "<img src=" . $show_logo . "><br>";
// Create a curl session
$ch = curl_init($show_logo);
// Execution
curl_exec($ch);
// Verification if an error occured
if(!curl_errno($ch))
{
$info = curl_getinfo($ch, $opt);
}
// Fermeture du gestionnaire
curl_close($ch);
if ($opt === FALSE) {
$show_logo = "http://placehold.it/165x100/&text={$ukip_code}";
}
echo $show_logo;
?>
try something like this -
$file = $_SERVER['DOCUMENT_ROOT'].'sitepathtofile';
if (!file_exists($file)) {
set the placeholder
}

Adding Text to End of the File PHP [duplicate]

This question already has answers here:
Need to write at beginning of file with PHP
(10 answers)
Closed 9 years ago.
I've got this PHP script:
<?php
if ('POST' === $_SERVER['REQUEST_METHOD'] && ($_POST['title'] != 'Title') && ($_POST['date'] != 'Date'))
{
$fileName = 'blog.txt';
$fp = fopen('blog.txt', 'a');
$savestring = PHP_EOL . "<h2><center><span>" . $_POST['title'] . "</span></center></h2>" . "<div class=fright><p><em>|<br><strong>| Posted:</strong><br>| " . $_POST['date'] . "<br>|</p></em></div></p></em>" . "<p><em>" . $_POST['paragraph'] . "</em></p>" . PHP_EOL . "<hr>";
fwrite($fp, $savestring);
fclose($fp);
header('Location: http://cod5showtime.url.ph/acp.html');
}
?>
It works perfectly but it has a slight problem. The text is added at the end of the file. Is there a way to make it add the $savestring at the beginning of the text file ? I'm using this for my blog and I just noticed this slight problem.
You need to use the correct writing mode:
$fp = fopen('blog.txt' 'c');
http://us1.php.net/manual/en/function.fopen.php
You can you use
$current = file_get_contents($file);
// Append a data to the file
$current .= "John Smith\n";
file_put_contents($file, $current, FILE_APPEND | LOCK_EX);

file_get_contents Warning: Failed to open stream

I have a question here, tho, I've been digging here at SO, it seems I can't find the real deal;
I am trying the ff:
<?php
$filename = $trantype . $delimiter . $dateToday . $fileExtension ;
//echo $filename . '<br/>';
$fileToOpen = $filepath . $filename;
echo "File To Open: " . $fileToOpen . '<br/>';
$string = file_get_contents($fileToOpen);
//$string = file_get_contents("../transactions/o/O_20120809.xx");
$json_array = json_decode($string, true);
echo "Echo: " . $json_array[0]['itemheader_sysid'] . '<br/>';
echo "The File Contents: " . $string;
?>
The $string = file_get_contents('../transaction/o/O_20120809.xx') works smoothly on the other hand the $string = file_get_contents($fileToOpen); doesn't seem to work and is giving me the ff: error;
Warning: file_get_contents(../transactions/o/0_20120809.xx) [function.file-get-contents]: failed to open stream: No such file or directory in C:\xampp\htdocs\xx\helper\upo.php on line 19
why so?
Anyone please?

PHP dump $_REQUEST to file

I want to dump request variables to a file for debugging. How's this possible?
<?php
$req_dump = print_r($_REQUEST, TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, $req_dump);
fclose($fp);
Untested but should do the job, just change request.log to the file you want to write to.
I think nowadays this method is easier and faster:
$req_dump = print_r($_REQUEST, true);
$fp = file_put_contents('request.log', $req_dump, FILE_APPEND);
Use serialize() function for dumping. Dump $_SERVER, $_COOKIE, $_POST and $_GET separately (may go to the same file). If you're planning on debugging with the data it helps to know if the data was part of a POST request or a GET request.
Dumping everything is good for debugging in development, but not so in production. If your application does not have many users, it can work in production too. If you anticipate many users, consider dumping just the $_POST data, or limit server variables to those starting with HTTP_.
/* may be late but he can help others.
it's not my code, I get it from :
https://gist.github.com/magnetikonline/650e30e485c0f91f2f40
*/
class DumpHTTPRequestToFile {
public function execute($targetFile) {
$data = sprintf(
"%s %s %s\n\nHTTP headers:\n",
$_SERVER['REQUEST_METHOD'],
$_SERVER['REQUEST_URI'],
$_SERVER['SERVER_PROTOCOL']
);
foreach ($this->getHeaderList() as $name => $value) {
$data .= $name . ': ' . $value . "\n";
}
$data .= "\nRequest body:\n";
file_put_contents(
$targetFile,
$data . file_get_contents('php://input') . "\n"
);
echo("Done!\n\n");
}
private function getHeaderList() {
$headerList = [];
foreach ($_SERVER as $name => $value) {
if (preg_match('/^HTTP_/',$name)) {
// convert HTTP_HEADER_NAME to Header-Name
$name = strtr(substr($name,5),'_',' ');
$name = ucwords(strtolower($name));
$name = strtr($name,' ','-');
// add to list
$headerList[$name] = $value;
}
}
return $headerList;
}
}
(new DumpHTTPRequestToFile)->execute('./dumprequest.txt');
// add this line at the end to create a file for each request with timestamp
$date = new DateTime();
rename("dumprequest.txt", "dumprequest" . $date->format('Y-m-d H:i:sP') . ".txt");
<?php //log
$razdelitel = '--------------------------------------------'.PHP_EOL . date("Y-m-d H:i:s") .PHP_EOL.PHP_EOL;
$data_REQUEST = '$_REQUEST: ' . print_r($_REQUEST, true).PHP_EOL;
$data_POST = '$_POST: ' . print_r($_POST, true).PHP_EOL;
$data_GET = '$_GET: ' . print_r($_GET, true).PHP_EOL;
$data_all = $razdelitel . $data_REQUEST . $data_POST . $data_GET;
$name_txt = __DIR__ . '/log_' . date('m.Y') . '.txt'; //log_12.2021.txt
$chmod = '0244';
chmod($name_txt, $chmod);
file_put_contents($name_txt, $data_all, FILE_APPEND);
//var_dump($name_txt, $chmod); ?>

Categories