I'm trying to detect whether an image exists on a remote server. However, I've tried several methods and can't get any of them to work.
Right now I'm trying to use this:
if (!CheckImageExists("http://img2.netcarshow.com/ABT-Audi_R8_2008_1024x768_wallpaper_01.jpg")) {
print_r("DOES NOT EXIST");
} else {
print_r("DOES EXIST");
};
function CheckImageExists($imgUrl) {
if (fopen($imgUrl, "r")) {
return true;
} else {
return false;
};
};
But it returns 'true' whether the image actually exists or not (the above image should, but change it to gibberish and it still will return 'true'). I have a feeling it could be because if the URL does not exist, it redirects to the homepage of the site. But I don't know how to detect that.
Thanks for any help!
Use cURL.
After fetching the resource, you can get the error code calling curl_errno().
The chances are you are getting a HTML page back into your $imgUrl that contains "404 image not found" or something similar.
You should be able to check the response for a code indicating that the request failed or redirected.
This should do the trick (using image size):
if (!CheckImageExists("http://www.google.com/intl/en_ALL/images/srpr/logo1w.png")) {
echo 'DOES NOT EXIST';
} else {
echo 'DOES EXIST';
};
function CheckImageExists($imgUrl) {
if (#GetImageSize($imgUrl)) {
return true;
} else {
return false;
};
};
Got it working with Seb's method. Just used YQL to inspect the actual content of the page and determine if it's an error or not.
Related
I am a novice and I work in PHP.
My English is not very good. If you see a typo, please edit it.
I need a function that changes the status of the site. Like the following function:
var_dump(http_response_code()); // return 200
function changeStatus($from, $to) {
// The code I need
}
changeStatus(200, 404);
var_dump(http_response_code()); // return 404
Is such a thing possible at all?
please guide me
This code will solve your problem
function changeStatus($response_code) {
// The code I need
http_response_code($response_code);
}
changeStatus(404);
var_dump(http_response_code());
This is wrong because it returns the previous result
var_dump(http_response_code(404)); // return 200
Try this. This answer is safer
function changeStatus($responseCode)
{
if (http_response_code($responseCode))
return true;
else
return false;
}
changeStatus(404);
I'm experiencing a very odd problem. Everything works as expected on my local host. When I upload to a live server, the page just cuts off right where I'm including a file. Just white space beneath it. Nada...
The line that breaks is:
<? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
And the file being included is:
<?php
/*///////////////////////////////////////////////////////////////////////
Part of the code from the book
Building Findable Websites: Web Standards, SEO, and Beyond
by Aarron Walter (aarron#buildingfindablewebsites.com)
http://buildingfindablewebsites.com
Distrbuted under Creative Commons license
http://creativecommons.org/licenses/by-sa/3.0/us/
///////////////////////////////////////////////////////////////////////*/
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('xxxxxxx');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "xxxxxx";
if($api->listSubscribe($list_id, $_GET['email']) === true) {
// It worked!
// return 'Success! Thank You!';
echo '<script> window.location.href = "thank-you.php"; </script>';
}
else
{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The only thing edited in the above code is the API key and List ID.
its because is missing parentesis on your if condition.
require_once('inc/store-address.php');
if($_GET['submit'] **)** {
echo storeAddress();
}
It seems there was an error. It was working on my local server because there wasn't an error.
I was using filezilla do upload my content. For some reason it appears to be an encoding issue when uploading.
I don't know if I should delete this question or answer to help someone else with the problem later on so I chose the later.
I manually uploaded my file and guess what, it works!
THIS is the PHP code m using for checking the values
if($uname==$row['username']) {
if($uname=='' || $pass=='') {
header("Location:login.html?id=Some fields are empty");
} else if($uname==$row['username'] && $pass==$row['password']) {
header("Location:1.html?id=$uname");
} else {
// **HERE I AM REDIRECTING TO THE LOGIN PAGE AND SENDING ERROR MESSAGE AS ID**
header("Location:login.html?id=Incorrect Password");
}
}
In the HTML part I included this to show the error message
<?php
if(isset($_GET['id']))
{
echo $_GET['id'];
}
?>
However NOTHING is getting printed
As mentioned in the comments, make sure that the server is set to parse .html file as PHP. See Server not parsing .html as PHP
The other option is to change your login.html to be login.php and go from there.
you can use php filters to check correctly if the values are set or not like the following :
filter_has_var(INPUT_GET , 'id');
this function returns true or false
Ok, am using traditional php, no frameworks, nothing, I am using simple procedural way, now my question is I was searching for a while but am not getting an answer to my question, I am not using .htaccess files as of now, but I really need to understand how 404 error works? I am having a website, where I show post's related to category, say category=php, so I pass this as a get request
$_GET['category'] == 'php';
Now currently what am doing is something like this :
$pocategory = $_GET['category'];
if($pocategory == 'php' || $pocategory == 'javascript') {
//Then show related posts
} else {
header('Location:404.php');
exit;
}
I mean I just want php and javascript as valid request's value, rest I want to redirect to 404 but am not understanding how to do it so I did this way, what if am having more than 50 categories? I cant list them all in this if condition, Inshort how to detect whether the given get request value is invalid or not..
Any help will be much appreciated.
.htaccess is the way to do this.
ErrorDocument 404 index.php?404
that line will tell apache what file to load. The example above calls the main index.php script.
add something like this to the top of your index.php file:
$error_404 = isset($_GET["404"]) ? true : false;
now you can detect if you have a 404 error request. $error_404 will be true, so why not add a simple function:
function error_404($error_404)
{
if($error_404 == true)
{
// do some error stuff here, like set headers, and some text to tell your visitor
}
}
now just call your function:
error_404($error_404);
best to do that immidiatley after the get handler:
error_404($error_404)
$error_404 = isset($_GET["404"]) ? true : false;
or combine the two into one line:
error_404($error_404 = isset($_GET["404"]) ? true : false);
to address the question, add this to the relevant script:
$pocategorys_ar = array("php","javascript");
if (!in_array($pocategory, $pocategorys_ar))
{
error_404(true);
}
Make sure it has access to the error_404() function.
You could put all categories inside an array like this:
$pocategories = array
(
'php',
'javascript'
);
if (in_array($pocategory, $pages))
{
// ...
}
else
{
header('Location:404.php');
}
Another thing you could do is creating a html/php file for every category and do it like so
if (is_file('sites/' . $popcategory . '.php')
{
include('sites/' . $popcategory . '.php');
}
else
{
header('Location:404.php');
}
I have a program that prints reports for a user id list. The program is supposed to print reports one by one for users on the list uploaded. The problem is that when I was running the printing process and getting to print the report with indexInList=30, I got error:
This webpage has a redirect loop
The webpage at http://127.0.0.1/content/8520?print=1&bulkprinting=1&filename=/private/var/tmp/phpHRXEw8.moved&indexInList=30&nopeergroup=1&nolabpage=0&hideScreeningOnly=1&showOnlyScreening=0&hideHoldMailing=1 has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
I tried to clean the cookie but still keep getting the same error.
I attached some code here and hope anyone can help me:
$sessionData['first_name'] = $foundUser->first_name;
$sessionData['last_name'] = $foundUser->last_name;
// Overwrite $_REQUEST variable with parameters before including
// the hpa report
$_REQUEST = array(
'user_id' => $foundUser->id,
'bulkprinting' => true
);
if($nopeergroup) { $_REQUEST['nopeergroup'] = $nopeergroup; }
if($nolabpage) { $_REQUEST['nolabpage'] = $nolabpage; }
if($hideScreeningOnly) { $_REQUEST['hideScreeningOnly'] = $hideScreeningOnly; }
if($showOnlyScreening) { $_REQUEST['showOnlyScreening'] = $showOnlyScreening; }
if($hideHoldMailing) { $_REQUEST['hideHoldMailing'] = $hideHoldMailing; }
$includeValue = include __DIR__.'/../hpa/hpa.php';
$url = sprintf(
"/content/8520?print=1&bulkprinting=1&filename=%s&indexInList=%s" .
"&nopeergroup=%s&nolabpage=%s&hideScreeningOnly=%s" .
"&showOnlyScreening=%s&hideHoldMailing=%s",
$filename, $indexInList, (int)$nopeergroup, (int)$nolabpage,
(int)$hideScreeningOnly, (int)$showOnlyScreening, (int)$hideHoldMailing);
if($hradata[0] !== false) {
$sessionData['hra_id'] = $hradata[0]['id'];
}
if($screeningdata[0] !== false) {
$sessionData['screening_id'] = $screeningdata[0]['id'];
}
if($includeValue !== 1) {
// Redirect to URL
$sessionData['message'] = $messages_set[$includeValue];
$_SESSION['printing_set'][] = $sessionData;
redirect($url);
}
$sessionData['markAsMailed'] = true;
$_SESSION['printing_set'][] = $sessionData;
?>
<script type="text/javascript">
function waitPrint() {
window.print();
var t = setTimeout("timed()", 1000);
}
function timed() {
window.location.replace("<?php echo $url ?>");
}
if(window.attachEvent) {
window.attachEvent("onload", waitPrint);
} else if(window.addEventListener) {
window.addEventListener("load", waitPrint, false);
}
</script>
Sounds like you have a lot of files that need printing!
You may be able to alter your browser settings (I seem to remember you can in Firefox) to allow more than 30 loops.
Alternatively, you could always limit your code to 30 loops then wait for further user interaction to proceed to the next 30.
The 3rd option is to always create a Word document or PDF with one report on each page, then save the file and print it - a little more hassle (in a way) but at least you'll be able to print everything at once.
In order for $includeValue to be set to anything, the file __DIR__.'/../hpa/hpa.php' must have a return statement inside of it, as demonstrated in the PHP documentation for include, example 5. include will only return a value when called if the included file returns a value.
If your script still produces an infinite loop, your logic within the included file is incorrect and it is consistently producing a value that is not 1.
Essentially, here is the code that your question boils down to:
$includeValue = include __DIR__.'/../hpa/hpa.php';
if($includeValue !== 1) {
// Redirect
}
Browsers have checks built-in to help you when sites are misconfigured into a redirection loop, and 30 must be the limit for the browser you're using. You've built a redirection loop on purpose, but the browser doesn't know that. Instead of using the window.location.replace() method, how about a form that automatically submits? That should look different to the browser, and allow your loop to progress as designed.
<script type="text/javascript">
function waitPrint() {
window.print();
var t = setTimeout("timed()", 1000);
}
function timed() {
window.reloadForm.submit();
}
if(window.attachEvent) {
window.attachEvent("onload", waitPrint);
} else if(window.addEventListener) {
window.addEventListener("load", waitPrint, false);
}
</script>
<form name="reloadForm" action="<?php echo $url ?>">
</form>