PHP file_get_contents foreach - php

I've found an existing script on the internet that grabs data from WHOIS servers and extracts the relevent data (Eg. Expiry date, Status). As it was long abandoned I have been modifying it and created my own script.php?id=domain.com which lets me enter any domain and whois data comes up,
What I'm having trouble with is I have my whois.php file which I want to grab a list of domains out of my MySQL database and attempt to extract the Expiry/Status data of each domain using (file_get_contents to my script.php and foreach) then update the database with the relevant information.
I'm fairly certain I have coded everything apart from the "Foreach" & "File_get_contents" part right therefore my script encounters errors.
"Warning: Invalid argument supplied for foreach() in /home/user/public_html/mydomain.com/domains/whois.php on line 39"
is the error I receive.
Snippet of my whois.php:
include("database.php");
// Select one domain from the database that hasn't been checked yet
$sql = "SELECT domainName from domains WHERE 1 ORDER BY lastChecked ASC";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$domain = $row[0];
if(mysql_num_rows($result) == 0){
die("No domains found in the database.");
}
// Grab the WHOIS information for the domain selected
// ---------------------------------------------------------------
$domainExt = substr($domain, -3); // grab the domain extension
//var_dump($whois);
$arr = array($content);
foreach($arr as $id) {
echo $id, '<br>';
$data = file_get_contents('http://codestrike.net/domains/script.php?id='.$domain.'');
echo $data, '<br>';
}
foreach($data as $whoisline){
if(strstr($whoisline,"Expiration")){
$whoisline = str_replace("Expire Date:","",$whoisline);
$whoisline = trim($whoisline);
$expiration = substr($whoisline,0,11);
}
if(strstr($whoisline,"Status")){
$statusline = $whoisline;
}
}
$status = str_replace("Status:","",$statusline);
$status = trim($status);
Script.php?id=domain.com works fine, its just a matter of having the whois.php finding the expiry date/status for each domain out of my MySQL Database.
Cheers.

Change:
$data = file_get_contents('http://mydomain.com/domains/script.php?id='.$domain.'');
to:
$data = file('http://mydomain.com/domains/script.php?id='.$domain);
file_get_contents returns the entire file as a single string. file splits it up into an array, where each element is a line of the file.
You also need to process $data in the first foreach loop. Otherwise, you're just overwriting $data each time through the loop, and the code that uses it just gets the last one.
include("database.php");
// Select one domain from the database that hasn't been checked yet
$sql = "SELECT domainName from domains WHERE 1 ORDER BY lastChecked ASC";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$domain = $row[0];
if(mysql_num_rows($result) == 0){
die("No domains found in the database.");
}
// Grab the WHOIS information for the domain selected
// ---------------------------------------------------------------
$domainExt = substr($domain, -3); // grab the domain extension
//var_dump($whois);
$arr = array($content);
foreach($arr as $id) {
echo $id, '<br>';
$data = file('http://mydomain.com/domains/script.php?id='.$domain);
var_dump($data); echo '<br>';
foreach($data as $whoisline){
if(strstr($whoisline,"Expiration")){
$whoisline = str_replace("Expire Date:","",$whoisline);
$whoisline = trim($whoisline);
$expiration = substr($whoisline,0,11);
}
if(strstr($whoisline,"Status")){
$statusline = $whoisline;
}
}
$status = str_replace("Status:","",$statusline);
$status = trim($status);
}

Related

Premature End of Script Headers?

I have a problem with the code, it is the premature execution error when using header.
Code:
<?php
session_start();
require 'config.php';
$prepend = "<span class='welcome'>";
$append = "</span>";
if (!isset($_SESSION['name'])) {
header("Location: login.php");
}
echo $prepend."Здравей ".$_SESSION['name'].$append."</br>";
if (isset($_POST['submit']))
{
$newname = mysql_real_escape_string($_POST['newname']);
$newpass = mysql_real_escape_string($_POST['newpass']);
$oldpass = mysql_real_escape_string($_POST['oldpass']);
$checkPass = "SELECT pass from admin WHERE pass = '$_POST[oldpass]'";
$rs = mysqli_query($connect,$checkPass);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($data > 0)
{
$query = "UPDATE admin SET pass ='".$_POST['newpass']."',name ='".$_POST['newname']."'" ;
$result = mysqli_query($connect, $query);
if ($result === true)
{
echo "Update sucessfuly!";
}
}
else {
header('Location: admin.php?failed=1');
}
}
?>
The first time when you open the page the else part is performed immediately and I can not understand why.
First you have 2 weird lines in your code:
$rs = mysqli_query($connect,$checkPass);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
Those function don't exist, in fact you probably used the mysql_...() ones, as it seems confirmed by the previous statements.
Now when you execute
$data = mysql_fetch_array($rs, MYSQLI_NUM);
then $data is an array (the next record returned) or FALSE (when no more record exist. And this statement should belong to a loop.
Anyway, in the current form of your code, when you execute if ($data > 0), it can't return anything significative since $data is an array.
So you must refactor all this piece of code according to your need (I guess you want to control that pass was really found by the previous query).
the first time you open page, the else part is executed because the session variables are not set, you need to set session variables first.
$_SESSION['sessionName']= $value;
you must have done this on some other page, if so, then please share the code.
and try using
if(mysqli_num_row($data)>0)
{
$query = "UPDATE admin SET
pass='".$_POST['newpass']."',name='".$_POST['newname']."'" ;
$result = mysqli_query($connect, $query);
if ($result === true)
{
echo "Update sucessfuly!";
}
}
else{
header('Location: admin.php?failed=1');
}
}
?>

Export data into an existing csv file using php

I'm trying to get data from my data base and load it into an existing csv file i get no errors but each time i check with the file it stills empty.
this is my PHP file :
<?
$server="XXXX";
$user="XXXX";
$password="XXXX";
$db="XXXX";
mysql_connect($server,$user,$password) or die('erreur au serveur');
mysql_select_db($db) or die('erreur db');
if ($file=fopen('XXXX/toERP/exportfactures.csv','w')!=FALSE){
$req='select * from facture';
$sql = mysql_query($req);
$cpt=1;
$response["factures"] = array();
$output=fopen('http://XXXXX/toERP/exportfactures.csv','w');
if (mysql_num_rows($sql) > 0) {
// looping through all results
// factures node
while ($row = mysql_fetch_array($sql)) {
// temp user array
$facture = array();
$facture["id_fac"] = $row["id_fac"];
$facture["id_client"] = $row["id_client"];
$facture["id_agent"] = $row["id_agent"];
$facture["montant"] = $row["montant"];
$facture["type_paiement"] = $row["type_paiement"];
$facture["id_prod"] = $row["id_prod"];
$facture["date_vente"] = $row["date_vente"];
// push single client into final response array
array_push($response["factures"], $facture);
}
foreach ($response["factures"] as $ligne){
var_dump($ligne);
fputcsv($output,$ligne) or die ('erreur');
echo $cpt."inserted";
$cpt++;
}
fclose($file);
} else {
echo "file not found";
}
}
?>
You are unable to write to an http location try changing it to a local directory.
fopen('\XXXX\toERP\factures.csv','w')
or just change the save location
$output = fopen('\XXXX\toERP\factures.csv','w');
fputcsv($output, explode(';',$ligne));
You are trying to open a file from remote server due to url example your have wrote. This is your most possible issue if you see the lines inserted by echo.
Here is the definition for fputcsv : http://php.net/manual/en/function.fputcsv.php
As the second argument, you need to provide an array with fields.
$ligne in your case, is an array with one element: ['factures'] which is another array, so you need to change the foreach to match the form below :
foreach ($response['factures'] as $ligne)
Also, as others mentioned: you need to select a local resource for the filename, and make sure you have the right to write on it.
this code worked for me :
<?
$server="mysql12.000webhost.com";
$user="a2258793_star";
$password="star123";
$db="a2258793_stores";
$con = mysql_connect($server,$user,$password) or die('erreur au serveur');
mysql_select_db($db) or die('erreur db');
mysql_select_db($db);
$file='toERP/factures.csv';
$fp = fopen($file,"w");
$sql = mysql_query("select * from facture") or die (mysql_error);
mysql_data_seek($sql,0);
while ($row = mysql_fetch_assoc($sql)){
$sep = "";
$comma = "";
foreach ($row as $name => $value)
{
$sep.=$comma.''.str_replace('','""',$value);
$comma =";";
}
$sep.="\n";
fputs($fp,$sep);
}
fclose($fp);
?>

View PHP (echo) output in Sublime Text 2 when the code is run from Android

I have an android app that runs a PHP script to insert some rows into a MySQL table on my home server. I need to perform some debugging for which I have placed some "echo" commands at strategic locations within my PHP script. However, since the script is being triggered by an Android app on my phone, I obviously can't view the results of those echo commands in my browser. Is there any workaround?
For what it's worth, here's the PHP script in question:
<?php
// Includes
require_once 'PROJdbconn.php';
// Run script only if the dump array is received
if($_POST){
echo "\nEntries received: ".count($_POST)."\n"; // TEST1: Get POST size
// Read POST array
$arr = 0;
foreach($_POST as $entry){
$tempentry = $entry;
$namenum = explode(",",$tempentry);
$names[$arr] = str_replace("_", " ", $namenum[1]);
$numbers[$arr] = preg_replace('/[^0-9]/','',$namenum[0]);
$arr += 1;
}
$namenum = NULL;
echo "\nEntries after parse: ".$arr."\n\n"; // TEST2: Get parse count
// Build SQL query
$sql = "INSERT INTO Contact_table (PHONE, NAME) VALUES ";
for ($i = 0; $i < $arr; ++$i){
$sql .= "('".$numbers[$i]."', '".$names[$i]."'),";
echo $i.". ".$numbers[$i]."--->".$names[$i]."\n"; // TEST3: dump names and numbers
}
$i = NULL;
$arr = NULL;
$names = NULL;
$numbers = NULL;
$sql = substr($sql,0,strlen($sql)-1)." ON DUPLICATE KEY UPDATE name = COALESCE(VALUES(name), name);";
// Connect to MySQL database
$connect = dbconn(PROJHOST,PROJDB,PROJDBUSER,PROJDBPWD);
// Execute SQL query
$query = $connect->query($sql);
$sql = NULL;
$query = NULL;
// Close connection to MySQL database
$connect = NULL;
}
?>
You can use a google chrome extension that can POST data to this PHP script. the extensions name is Postman - REST Client. Its a very easy tool to use :).

loading a xml file instead of download

Hey guys I have stored few xml files in database and want to get them for xslt transformation. But I am unable to load it for transformation, they get downloaded to PC. I want to process it instead of download.
here is my code: I am accessing the file with its id.
// Fetch the file information
$query = "
SELECT `pname`,`pdata`
FROM `plist`
WHERE `pid` = {$id}";
$result = $dbLink->query($query);
if ($result) {
// Make sure the result is valid
if ($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_row($result);
echo "$row[0]";
header("Content-Type:text/xml");
header("Content-Disposition: inline");
echo $row['pdata'];
}
mysqli_free_result($result);
---missing something here to get file data--
until now it gets downloaded but i want to continue the transformation
$xml = new DOMDocument;
$xml->load(what goes here??);
$xsl = new DOMDocument;
$xsl->load('file.xslt');
//etc
any help appreciated.
If you have a string with the XML then you can use $xml->loadXML($row['pdata']) I think to parse the XML.
Working solution that i found later enjoy..:)
<?php
if (isset($_GET['id'])) {
// Get the id
$id = intval($_GET['id']);
// Make sure the name is in fact a valid
if ($id <= 0) {
die('The id is invalid!');
} else {
// Connect to the database
include 'config.php';
}
// Fetch the file information
$query = "select id, name, data from data_table where id ={$id};";
$resultx = $mysqli->query($query) or die($mysqli->error . __LINE__);
$arr = array();
if ($resultx->num_rows > 0) {
while ($row = $resultx->fetch_assoc()) {
$arr[] = $row['tdata'];
}
}
$string = implode(",", $arr);
// Load XML file
$xml = new DOMDocument; // create new document
$xml->loadXML($string); // load string to it

function and class to show image not working in php

i am trying to get get the following working nothing is happen when i use the function i am trying to get it to display images
class ItemRes {
//items DB
var $img="";
}
function ShowItemImage($index,$res_a){
if(sizeof($res_a) > $index){
if($res_a[$index] != NULL) {
$cimg = $res_a[$index]->img;
return "<img src='$cimg' width='70' height='70' style='cursor:pointer'></img>";
}
}else{
return "<center class='whitetxt'><strong>Empty</strong></center>";
}
}
$res_array = array();
$idx=0;
$result21 = mysql_query("SELECT * FROM photos WHERE eid='$eid' ORDER BY id DESC") or die (mysql_error());
while ($row21 = mysql_fetch_array($result21)) {
$img_path = $row21['path'];
$obj = new ItemRes();
$obj->img = $img_path;
$res_array[$idx] = $obj;
$idx++;
}
ShowItemImage(0,$res_array)
ShowItemImage(1,$res_array)
Thhere are many issues with this code, so I'll just take them one at the time.
Assuming you initiate the database connection somewhere else the first issue is
the line:
$result21 = mysql_query("SELECT * FROM photos WHERE eid='$eid' ORDER BY id DESC") or die (mysql_error());
Prior to this line you do not set the variable $eid and thus this will only fetch items with eid = ''
Second:
You do not end the last two rows with a semicolon, thus this will produce a fatal error.
Third:
Probably the reason to why you get 'nothing is happen' (wich I interpet as a blank page)
In your function ShowItemImage you return strings but you do nothing with them.
You need to change this:
ShowItemImage(0,$res_array)
ShowItemImage(1,$res_array)
to:
echo ShowItemImage(0,$res_array);
echo ShowItemImage(1,$res_array);
and you will probably start noticing some things on the screen.

Categories